public ObservableTranslationItem(TranslationItem item)
 {
     this.Id = item.Id;
     this.Name = item.Name;
     this.Translator = item.Translator;
     this.Exists = item.Exists;
     this.LocalPath = Path.Combine(FileUtils.GetQuranDatabaseDirectory(), item.Filename);
     _isCompressed = item.Compressed;
     _serverUrl = item.Url;
 }
 public ObservableTranslationItem(TranslationItem item)
     : base()
 {
     this.Id = item.Id;
     this.Name = item.Name;
     this.Translator = item.Translator;
     this.ServerUrl = item.Url;
     this.FileName = item.Filename;
     this.Exists = item.Exists;
     this.LocalUrl = PathHelper.Combine(FileUtils.GetQuranDatabaseDirectory(false, true), this.FileName);
     this.IsCompressed = item.Compressed;
 }
        public static async Task<IEnumerable<TranslationItem>> DownloadTranslations(bool useCache, string tag)
        {
            bool shouldUseCache = false;
            if (useCache)
            {
                var when = SettingsUtils.Get<DateTime>(Constants.PREF_LAST_UPDATED_TRANSLATIONS);
                var now = DateTime.Now;
                if (when.AddMilliseconds(Constants.MIN_TRANSLATION_REFRESH_TIME) > now)
                {
                    shouldUseCache = true;
                }
            }

            string text = null;
            if (shouldUseCache)
            {
                text = loadCachedResponse();
            }

            bool refreshed = false;
            if (string.IsNullOrEmpty(text))
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(WEB_SERVICE_URL);
                request.Method = HttpMethod.Get;
                var response = await request.GetResponseAsync();
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    text = sr.ReadToEnd();
                }

                if (string.IsNullOrEmpty(text))
                {
                    text = loadCachedResponse();
                }

                if (string.IsNullOrEmpty(text))
                {
                    return null;
                }

                if (useCache)
                {
                    cacheResponse(text);
                }
                refreshed = true;
            }

            TranslationsDatabaseHandler adapter = new TranslationsDatabaseHandler();
            var cachedItems = adapter.GetTranslations();
            List<TranslationItem> items = new List<TranslationItem>();
            List<TranslationItem> updates = new List<TranslationItem>();
            
            try
            {
                var token = JObject.Parse(text);
                foreach(var t in token["data"]) 
                {
                    TranslationItem item = new TranslationItem();
                    item.Id = t["id"].ToObject<int>();
                    item.Name = (string)t["displayName"];
                    item.Translator = (string)t["translator_foreign"];
                    if (string.IsNullOrEmpty(item.Translator))
                        item.Translator = (string)t["translator"];
                    item.LatestVersion = t["current_version"].ToObject<int>();
                    item.Filename = (string)t["fileName"];
                    item.Url = (string)t["fileUrl"];
                    if (item.Url.EndsWith("ext=zip", StringComparison.OrdinalIgnoreCase))
                        item.Compressed = true;
                

                    int firstParen = item.Name.IndexOf("(");
                    if (firstParen != -1)
                    {
                        item.Name = item.Name.Substring(0, firstParen - 1);
                    }

                    string databaseDir = FileUtils.GetQuranDatabaseDirectory(false);
                    item.Exists = FileUtils.FileExists(FileUtils.Combine(databaseDir, item.Filename));

                    bool needsUpdate = false;
                    TranslationItem localItem = cachedItems.Where(ti => ti.Id == item.Id).FirstOrDefault();
                    if (item.Exists)
                    {
                        if (localItem != null)
                        {
                            item.LocalVersion = localItem.LocalVersion;
                        }
                        else if (item.LatestVersion > -1)
                        {
                            needsUpdate = true;
                            try
                            {
                                using (var mHandler = new QuranDatabaseHandler<QuranAyah>(item.Filename))
                                {
                                    item.LocalVersion = mHandler.GetTextVersion();
                                }
                            }
                            catch
                            {
                                Debug.WriteLine("exception opening database: " + item.Filename);
                            }
                        }
                        else 
                        { 
                            needsUpdate = true; 
                        }
                    }
                    else if (localItem != null)
                    {
                        needsUpdate = true;
                    }

                    if (needsUpdate)
                    {
                        updates.Add(item);
                    }

                    items.Add(item);
                }

                if (refreshed)
                {
                    SettingsUtils.Set<DateTime>(Constants.PREF_LAST_UPDATED_TRANSLATIONS, DateTime.Now);
                }

                if (updates.Count() > 0)
                {
                    adapter.WriteTranslationUpdates(updates);
                }
            }
            catch (Exception je)
            {
                Debug.WriteLine("error parsing json: " + je.Message);
            }

            return items;
        }
        public static async Task<IEnumerable<TranslationItem>> DownloadTranslations(bool useCache, string tag)
        {
            bool shouldUseCache = false;
            if (useCache)
            {
                var when = SettingsUtils.Get<DateTime>(Constants.PREF_LAST_UPDATED_TRANSLATIONS);
                var now = DateTime.Now;
                if (when.AddMilliseconds(Constants.MIN_TRANSLATION_REFRESH_TIME) > now)
                {
                    shouldUseCache = true;
                }
            }

            string text = null;
            if (shouldUseCache)
            {
                text = await LoadCachedResponse();
            }

            bool refreshed = false;
            if (string.IsNullOrEmpty(text))
            {
                HttpClient httpClient = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, WEB_SERVICE_URL);
                var response = await httpClient.SendAsync(request);
                text = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(text))
                {
                    text = await LoadCachedResponse();
                }

                if (string.IsNullOrEmpty(text))
                {
                    return null;
                }

                if (useCache)
                {
                    await CacheResponse(text);
                }
                refreshed = true;
            }

            List<TranslationItem> items = new List<TranslationItem>();
            
            try
            {
                var token = JObject.Parse(text);
                foreach(var t in token["data"]) 
                {
                    TranslationItem item = new TranslationItem();
                    item.Id = t["id"].ToObject<int>();
                    item.Name = (string)t["displayName"];
                    item.Translator = (string)t["translator_foreign"];
                    if (string.IsNullOrEmpty(item.Translator))
                        item.Translator = (string)t["translator"];
                    item.LatestVersion = t["current_version"].ToObject<int>();
                    item.Filename = (string)t["fileName"];
                    item.Url = (string)t["fileUrl"];
                    if (item.Url.EndsWith("ext=zip", StringComparison.OrdinalIgnoreCase))
                        item.Compressed = true;
                

                    int firstParen = item.Name.IndexOf("(");
                    if (firstParen != -1)
                    {
                        item.Name = item.Name.Substring(0, firstParen - 1);
                    }

                    item.Exists = await FileUtils.FileExists(FileUtils.DatabaseFolder, item.Filename);

                    items.Add(item);
                }

                if (refreshed)
                {
                    SettingsUtils.Set<DateTime>(Constants.PREF_LAST_UPDATED_TRANSLATIONS, DateTime.Now);
                }
            }
            catch (JsonException je)
            {
                telemetry.TrackException(je, new Dictionary<string, string> { { "Scenario", "ParsingDownloadedTranslationJson" } });
            }

            return items;
        }