internal static void DownloadSeriesInformation(IMLItem item, string parentDir,
            ref string seriesName, ref string seriesID, bool fileServerIsOnline,
            bool isUNC, TVDBLib tvdb,string mdfSettingsb, IBaseSystem iBaseSystem )
        {


            if (String.IsNullOrEmpty(seriesName))
                return;

            WebClient client = new WebClient();
            bool foundSeries;

            TVdbTvEpisodeDetailsDownloaderHelpers.NormalizeSeriesName(ref seriesName);


            if (TVdbTvEpisodeDetailsDownloaderHelpers.GetSeriesMatchFromSectionOrTVDb(item, ref seriesName, out seriesID,
                tvdb, mdfSettingsb, iBaseSystem, out foundSeries))
                return;


            GetEpisodeKeysFromItemTagsAndPopulateEpisodeMetadata(item, seriesName, 
                seriesID, fileServerIsOnline, isUNC, tvdb, mdfSettingsb,
                iBaseSystem, client, foundSeries);
     
        
        }
        private static void GetEpisodeKeysFromItemTagsAndPopulateEpisodeMetadata
            (IMLItem item, string seriesName,
                            string seriesID, bool fileServerIsOnline,
                            bool isUNC, TVDBLib tvdb, string mdfSettingsb,
                            IBaseSystem iBaseSystem, WebClient client,
                            bool foundSeries)
        {

            if (!foundSeries)
            {
                MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                "Series with name " + seriesName + " was not found.");

                Thread.Sleep(2000);
                
                return;
            
            }

            string episodeID = Helpers.GetTagValueFromItem(item, "EpisodeID");

            if (!String.IsNullOrEmpty(episodeID))
                return;
            
            int episodeNumber;
            int seasonNumber;

            if (TVdbTvEpisodeDetailsDownloaderHelpers
                .GetEpisodeKeysFromItemTags
                (item, out episodeNumber, out seasonNumber))
                return;

            if (seasonNumber == 0 || episodeNumber == 0)
                return;

            ITVDBEpisode episode;
            ITVDBSeries series;


            if (TVdbTvEpisodeDetailsDownloaderHelpers
                .GetSeriesAndEpisodeFromTVDb(seriesName, seriesID, tvdb,
                        episodeNumber, seasonNumber,
                        out episode, out series))
                return;


            TVdbTvEpisodeDetailsDownloaderHelpers
                .PopulateEpisodeMetadata
                (item, fileServerIsOnline, isUNC,
                        mdfSettingsb,
                        iBaseSystem, seasonNumber, client,
                        series,
                        episode);



        }
        internal static bool SearchTVDbForSeries(string seriesName, TVDBLib tvdb, out IList<ITVDBSeries> seriesResults)
        {

            try
            {
                Debugger.LogMessageToFile("Searching TVdb for Series: " + seriesName + "...");
                MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                "Searching for Series " + seriesName + "...");

                seriesResults = tvdb.SearchSeries(seriesName);
            
            }
            catch (Exception)
            {

                MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                "TVdb did not respond. Retrying...");

                try
                {
                    seriesResults = tvdb.SearchSeries(seriesName);
                }
                catch (Exception)
                {

                    Debugger.LogMessageToFile("Communication with TVdb failed. Cannot identify this series.");
                    StatusForm.statusForm.TrayIcon.ShowBalloonTip(2000, "Communication with TVdb failed",
                    "MediaFairy was unable to connect to TVdb." +
                    " Please check your internet connection availability," +
                    " otherwise the online database may be temporarily offline or unreachable.",
                    ToolTipIcon.Warning);

                    Thread.Sleep(3000);

                    seriesResults = null;
                    return true;
                
                }

            }

            return false;

        }
        internal static bool GetSeriesAndEpisodeFromTVDb(string seriesName, string seriesID, TVDBLib tvdb, int episodeNumber,
                                                        int seasonNumber, out ITVDBEpisode episode, out ITVDBSeries series)
        {
            if (GetSeriesFromTVDb(seriesName, seriesID, tvdb, out series))
            {
                episode = null;
                return true;
            }

            return GetEpisodeFromTvDb(seriesName, seriesID, tvdb,
                                      seasonNumber, episodeNumber, out episode);

        }
        internal static bool GetSeriesFromTVDb(string seriesName, string seriesID,
                                              TVDBLib tvdb, out ITVDBSeries series)
        {

            Debugger.LogMessageToFile("Getting information for Series " + seriesName + "...");
            MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                                                      "Getting information for Series " + seriesName + "...");

            try
            {
                series = tvdb.GetSeries(seriesID);
            }
            catch
            {
                MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                                                          "TVdb did not respond. Retrying...");

                try
                {
                    series = tvdb.GetSeries(seriesID);
                }
                catch (Exception)
                {
                    Debugger.LogMessageToFile("Unable to connect to TVdb." +
                                              " Cannot get information for this Series.");
                    
                    StatusForm.statusForm.TrayIcon.ShowBalloonTip(2000, "Unable to connect to TVdb",
                                                                  "MediaFairy was unable to contact TVdb database in order to download episode information. Please check your internet connection availability, otherwise the online database may be temporarily unavailable.",
                                                                  ToolTipIcon.Info);

                    Thread.Sleep(2000);
                    series = null;
                    return true;

                }

            }

            return false;
        
        }
        internal static bool GetSeriesMatchFromSectionOrTVDb(IMLItem item, ref string seriesName, out string SeriesID,
                                                            TVDBLib tvdb, string mdfSettingsb, IBaseSystem IBS,
                                                            out bool foundSeries)
        {


            var seriesItems = SearchForSeriesInSection(seriesName);


            if (seriesItems.Count > 0)
            {
                foundSeries = GetSeriesKeysFromLocalMatch(seriesName, out SeriesID, seriesItems);

                if (string.IsNullOrEmpty(SeriesID))
                {
                    if (GetSeriesKeysFromTVDb(item, ref seriesName, out SeriesID, tvdb,
                            mdfSettingsb, IBS, seriesItems, out foundSeries))
                        return true;
                }

            }
            else
            {
                if (GetSeriesKeysFromTVDb(item, ref seriesName, out SeriesID, tvdb,
                                            mdfSettingsb, IBS, seriesItems, out foundSeries))
                    return true;
            }

            return false;
    
        
        }
        internal static bool GetSeriesKeysFromTVDb(IMLItem item, ref string seriesName,
            out string seriesID, TVDBLib tvdb, string mdfSettingsb,
            IBaseSystem iBaseSystem, IMLItemList seriesItems,
            out bool foundSeries)
        {
            IList<ITVDBSeries> seriesResults;

            if (SearchTVDbForSeries
                (seriesName, tvdb, out seriesResults))
            {
                seriesID = null;
                foundSeries = false;
                return true;
            }


            foundSeries = IfSeriesWasFoundPopulateSeriesDetailsElseMarkAsNotListed
                (item, ref seriesName, out seriesID, mdfSettingsb, iBaseSystem, seriesItems, seriesResults);

            return false;
        }
        internal static TVDBLib ConnectToTVDb(ConnectionResult connectionResult)
        {

            if (!connectionResult.InternetConnectionAvailable && Settings.ConnectionDiagnosticsEnabled)
            {

                Helpers.UpdateProgress("Updating TV sections...",
                       "Internet connection was not detected. " +
                       "MediaFairy will not update TV Series libraries.",
                       null);

                Debugger.LogMessageToFile("Internet connection was not detected." +
                                          " MediaFairy will not update TV Series libraries.");
              

                return null;

            }


            Helpers.UpdateProgress("Updating TV Shows Section...", "Connecting to TVDb..", null);
            Debugger.LogMessageToFile("Connecting to TVDb...");


            TVDBLib tvdb;

            try
            {
                tvdb = new TVDBLib();

                Helpers.UpdateProgress("Updating TV Shows Section...", "Connection to TVDb was successful.", null);
                Debugger.LogMessageToFile("Connection to TVDb was succesful!");
            
            }
            catch (Exception)
            {
                try
                {

                    tvdb = new TVDBLib();

                    Helpers.UpdateProgress("Updating TV Shows Section...", "Connection to TVDb was successful.", null);
                    Debugger.LogMessageToFile("Connection to TVDb was succesful!");
                
                }
                catch (Exception)
                {

                    StatusForm.statusForm.TrayIcon.ShowBalloonTip(2000, "Communication with TVdb failed",
                    "MediaFairy was unable to connect to the TVdb database. " +
                    "Please check your internet connection availability," +
                    " otherwise the online database may be temporarily offline or unreachable.",
                    ToolTipIcon.Warning);

                    Debugger.LogMessageToFile("Unable to connect to TVDb. " +
                                              "MediaFairy will not update TV Series libraries.");
                    
                    Thread.Sleep(2000);

                    return null;
                
                }
            
            }

            return tvdb;


        }
 public ITVDBEpisode GetEpisode(string seriesID, int seasonNum, int episodeNum, TVDBLib.EpisodeOrderEnum order)
 {
   try
   {
     return this._db.GetEpisode(seriesID, this._langAbbrev, seasonNum, episodeNum, order);
   }
   catch (Exception ex)
   {
     throw ex;
   }
 }
        public static bool DownloadSeriesBanner(IMLItem Item, string BannerType, int SeasonNumber, string SeasonID, string ImageFile)
        {
            string posterUrl = "";
            byte[] imageData;


            try
            {

                #region define local variables
                TVDBLib tvdb = new TVDBLib();

                string SeriesID = Helpers.GetTagValueFromItem(Item,"SeriesID");

                #endregion


                string banner = Helpers.GetTagValueFromItem(Item, BannerType);
                #region check if image file in item's location exists
                if (!String.IsNullOrEmpty(banner))
                {
                    if (File.Exists(banner))
                        return true;
                }
                #endregion

                Application.DoEvents();


                #region look for backdrop in item's location and save to image tag
                if (File.Exists(ImageFile))
                {
                    Item.Tags[BannerType] = ImageFile;
                    Item.SaveTags();
                    return true;
                }
                #endregion


                //MessageBox.Show("Step 6");

                //MessageBox.Show(SeriesID);
                #region request and return image URLs

                IList<TVDBLibrary.ITVDBBanner> banners;
               

                try
                {
                    Helpers.UpdateProgress("Updating TV Section", "Searching TVdb for " + BannerType + " for '" + Item.Name + "'...", Item);
                    //MessageBox.Show("Step 7");

                    if (BannerType == "SeriesBanner")
                        banners = tvdb.GetSeriesBanners(SeriesID);
                    else if (BannerType == "Fanart")
                        banners = tvdb.GetSeriesFanart(SeriesID);
                    else banners = tvdb.GetSeasonImagesPoster(SeriesID, SeasonNumber);

                    //if (BannerType == "SeriesPoster")
                                           

                }
                catch (Exception)
                {
                    try
                    {
                        Helpers.UpdateProgress("Updating TV Section", "TVdb did not respond. Retrying...",  Item);

                        if (BannerType == "SeriesBanner")
                            banners = tvdb.GetSeriesBanners(SeriesID);
                        else if (BannerType == "Fanart")
                            banners = tvdb.GetSeriesFanart(SeriesID);
                        else banners = tvdb.GetSeasonImagesPoster(SeriesID, SeasonNumber);

                        //if (BannerType == "SeriesPoster")

                    }
                    catch
                    {
                        return false;
                    }

                }

                //MessageBox.Show("Step 8");

                #region cancel operation if no backdrop found
                if (banners.Count == 0)
                {
                    Item.Tags["LastUpdated"] = DateTime.Today.Date.ToString();
                    Item.SaveTags();
                    //Importer.thisProgress.Progress(Importer.CurrentProgress, "backdrop not found." + MovieName + ".");
                    //Thread.Sleep(500);
                    return false;
                }
                #endregion

                #endregion


                posterUrl = UI.UserSelectsSeriesBanner(Item, banners, BannerType );


                #region Download, save and import backdrop

                #region download the image
                Helpers.UpdateProgress("Updating TV Section", "Downloading Series " + BannerType + " from TVdb...",  Item);
                imageData = Downloaders.TrytoDownloadData(posterUrl, "TV", "TVdb", Item );

                if (imageData == null)
                    return false;

                #endregion

                #region save the image & update tags
                //MessageBox.Show("filepath: " + filepath);

                bool IsPoster = false;
                if (BannerType == "SeriesBanner")
                    IsPoster = true;

                if (BannerType == "backdrop")
                    BannerType = "Fanart";

                if ( ImageFileConstructor.SaveImage(imageData, Item, IsPoster, BannerType,ImageFile) != "")
                {
                    return true;
                }
                else return false;
                #endregion

                #endregion


            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return false;
            }


        }
 public IList<ITVDBUpdate> GetUpdates(TVDBLib.TimeConstraintEnum timeConstraint)
 {
   try
   {
     List<ITVDBUpdate> list = new List<ITVDBUpdate>();
     FastZip fastZip = new FastZip();
     string targetDirectory = Path.GetTempPath();
     if (!targetDirectory.EndsWith("\\"))
       targetDirectory = targetDirectory + "\\";
     string str1 = targetDirectory + "updates.zip";
     string str2 = targetDirectory + "updates_" + ((object) timeConstraint).ToString().ToLower() + ".xml";
     string zipUrl = this.GetZipURL();
     StringBuilder stringBuilder = new StringBuilder();
     stringBuilder.Append(zipUrl);
     stringBuilder.Append("C315A8864A6B7866");
     stringBuilder.Append("/updates/updates_");
     stringBuilder.Append(((object) timeConstraint).ToString().ToLower());
     stringBuilder.Append(".zip");
     WebClient webClient = new WebClient();
     webClient.DownloadFile(((object) stringBuilder).ToString(), str1);
     webClient.Dispose();
     if (System.IO.File.Exists(str2))
       System.IO.File.Delete(str2);
     fastZip.ExtractZip(str1, targetDirectory, "");
     if (System.IO.File.Exists(str2))
     {
       XmlDocument xmlDocument = new XmlDocument();
       xmlDocument.Load(str2);
       XmlNodeList xmlNodeList1 = xmlDocument.SelectNodes("/Data/Series");
       if (xmlNodeList1 != null)
       {
         foreach (XmlNode node in xmlNodeList1)
         {
           TVDBUpdate updateData = this.GetUpdateData(node);
           if (updateData != null && updateData.ID.Trim() != "")
             list.Add((ITVDBUpdate) updateData);
         }
       }
       XmlNodeList xmlNodeList2 = xmlDocument.SelectNodes("/Data/Episode");
       if (xmlNodeList2 != null)
       {
         foreach (XmlNode node in xmlNodeList2)
         {
           TVDBUpdate updateData = this.GetUpdateData(node);
           if (updateData != null && updateData.ID.Trim() != "")
             list.Add((ITVDBUpdate) updateData);
         }
       }
       XmlNodeList xmlNodeList3 = xmlDocument.SelectNodes("/Data/Banner");
       if (xmlNodeList3 != null)
       {
         foreach (XmlNode node in xmlNodeList3)
         {
           TVDBUpdate updateData = this.GetUpdateData(node);
           if (updateData != null && updateData.ID.Trim() != "")
             list.Add((ITVDBUpdate) updateData);
         }
       }
     }
     return (IList<ITVDBUpdate>) list;
   }
   catch (Exception ex)
   {
     throw ex;
   }
 }
 public ITVDBEpisode GetEpisode(string seriesID, string langAbbrev, int seasonNum, int episodeNum, TVDBLib.EpisodeOrderEnum order)
 {
   try
   {
     TVDBEpisode tvdbEpisode = (TVDBEpisode) null;
     string xmlurl = this.GetXMLURL();
     StringBuilder stringBuilder = new StringBuilder();
     stringBuilder.Append(xmlurl);
     stringBuilder.Append("C315A8864A6B7866");
     stringBuilder.Append("/series/");
     stringBuilder.Append(seriesID);
     if (order == TVDBLib.EpisodeOrderEnum.Absolute)
     {
       stringBuilder.Append("/absolute/");
       stringBuilder.Append(episodeNum.ToString());
     }
     else if (order == TVDBLib.EpisodeOrderEnum.DVD)
     {
       stringBuilder.Append("/dvd/");
       stringBuilder.Append(seasonNum.ToString());
       stringBuilder.Append("/");
       stringBuilder.Append(episodeNum.ToString());
     }
     else
     {
       stringBuilder.Append("/default/");
       stringBuilder.Append(seasonNum.ToString());
       stringBuilder.Append("/");
       stringBuilder.Append(episodeNum.ToString());
     }
     stringBuilder.Append("/");
     stringBuilder.Append(langAbbrev);
     stringBuilder.Append(".xml");
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.Load(((object) stringBuilder).ToString());
     XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/Data/Episode");
     if (xmlNodeList != null && xmlNodeList.Count > 0)
       tvdbEpisode = this.GetEpisodeData(xmlNodeList[0]);
     return (ITVDBEpisode) tvdbEpisode;
   }
   catch (Exception ex)
   {
     throw ex;
   }
 }
        internal static string DownloadSeriesAndEpisodeDetails
            (bool fileServerIsOnline, string mdfSettingsb,
             IBaseSystem ibs, TVDBLib tvdb, bool isUNC,
             string seriesID, IMLItem item,
             string parentDir, out string imdbid)
        {
            string moviehash = String.Empty;

            if (Helpers.GetTagValueFromItem
                (item, "MediaFairy-processed") != "--processed--")
            {
                string seriesName;

                moviehash = ExtractKeyFieldsForOnlineMetadataSearch
                    (item, out seriesName, out imdbid);



                TVDbTvEpisodeDetailsDownloader
                    .DownloadSeriesInformation
                    (item, parentDir, ref seriesName, 
                     ref seriesID, fileServerIsOnline, 
                     isUNC, tvdb, mdfSettingsb, ibs);



            }

            imdbid = String.Empty;

            return moviehash;

        }
        internal static bool PerfrormOnlineTasks
            (bool fileServerChecked,
            bool fileServerIsOnline,
            ConnectionResult connectionresult,
            string mdfSettingsb, 
            IBaseSystem iBaseSystem,
            TVDBLib tvdb,
            int currentItem, string location,
            bool isMultipart, string[] multipart,
            IMLItem item, bool isUNC, string seriesID,
            string parentDir)
        {

            if (!connectionresult.InternetConnectionAvailable &&
                Settings.ConnectionDiagnosticsEnabled)
                return true;
            
            string imdbid;
            
            string moviehash = DownloadSeriesAndEpisodeDetails
                (fileServerIsOnline, mdfSettingsb, iBaseSystem,
                 tvdb, isUNC, seriesID, item, parentDir, out imdbid);


            return PerfromMediaOrganizingAndDownloadSubtitle
                (fileServerChecked, fileServerIsOnline,
                 connectionresult, currentItem,
                 isMultipart, imdbid, moviehash, location, item, multipart);



        }
        internal static bool GetEpisodeFromTvDb(string seriesName, string seriesID, TVDBLib tvdb, int seasonNumber,
                                               int episodeNumber, out ITVDBEpisode episode)
        {
            try
            {
                Debugger.LogMessageToFile("Getting information for Season " + seasonNumber + ", Episode " +
                                          Convert.ToString(episodeNumber) + " of " + seriesName + "...");
                
                MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                                                          "Getting information for Season " + seasonNumber + ", Episode " +
                                                          Convert.ToString(episodeNumber) + " of " + seriesName + "...");
            
                episode = tvdb.GetEpisode(seriesID, seasonNumber, episodeNumber, TVDBLib.EpisodeOrderEnum.Default);
           
            }
            catch
            {
                try
                {
                    MainImportingEngine.ThisProgress.Progress(MainImportingEngine.CurrentProgress,
                                                              "TVdb did not respond. Retrying...");

                    episode = tvdb.GetEpisode(seriesID, seasonNumber,
                                              episodeNumber, TVDBLib.EpisodeOrderEnum.Default);
             
                }
                catch (Exception e)
                {

                    Debugger.LogMessageToFile("Unable to connect to TVdb. Cannot download Episode information.");
                    
                    StatusForm.statusForm.TrayIcon.ShowBalloonTip(2000, "Unable to connect to TVdb",
                                                                  "MediaFairy was unable to contact TVdb database in order to download episode information. " +
                                                                  "Please check your internet connection availability, " +
                                                                  "otherwise the online database may be temporarily unavailable.",
                                                                  ToolTipIcon.Info);

                    Thread.Sleep(2000);

                    episode = null;
                    
                    return true;
                
                }

            }

            return false;
        
        }
        internal static bool UpdateTvEpisodeItem
            (IMLSection section, ref bool fileServerChecked, 
             ref bool fileServerIsOnline,
             ConnectionResult connectionresult,
             string mdfSettingsb, IBaseSystem iBaseSystem,
             IEnumerable<string> combinedSceneTags, 
             TVDBLib tvdb, int totalItems, int id,
             ref int currentItem)
        {



            #region item variables

            IMLItem item = MediaSectionsAllocator.TvEpisodesSection.FindItemByID(id);
            string seriesID = string.Empty;

            //TODO: This var should be removed!
            const bool isMultipart = false;
            
            string location = item.Location;

            //TODO: This var must be removed!
            string[] multipart = new string[] {};
            
            bool isUNC = false;

            DirectoryInfo root;

            var parentDir = GetParentAndRootDirectories(location, out root);

            SingleTvEpisodeItemUpdaterHelpers.UpdateProgressTexts(totalItems, currentItem, item);

            #endregion

            try
            {


                #region Skip Not Listed item
                if (Helpers.GetTagValueFromItem(item, "NotListed") == "true")
                    return true;

                if (Helpers.UserCancels(MainImportingEngine.SpecialStatus, item))
                    return false;
                #endregion



                FileServerDiagnostic.CheckFileServer
                    (Settings.WantFileserverDiagnostics,
                    location, ref isUNC, ref fileServerChecked,
                    root.FullName, ref fileServerIsOnline);



                if (Helpers.UserCancels(MainImportingEngine.SpecialStatus, item))
                    return false;

                #region Delete Missing Item

                if (MissingItemRemover.DeleteMissingItem(Settings.DeleteMissing, isUNC, fileServerIsOnline, location,
                                                         section, item))
                    return true;

                if (Helpers.UserCancels(MainImportingEngine.SpecialStatus, item))
                    return false;
                
                #endregion


                if (EpisodeFileMetadataExtractor.ExtractMetadataFromEpisodeFilename
                        (item, location, section, MediaSectionsAllocator.TvEpisodesSection,
                        true, combinedSceneTags))
                    return true;
                

                if (Helpers.UserCancels(MainImportingEngine.SpecialStatus, item))
                    return false;



                #region Calculate Video Hash

                TvSeriesOperations.CalculateVideoHash(item, fileServerIsOnline, isUNC, location);
                
                if (Helpers.UserCancels(MainImportingEngine.SpecialStatus, item))
                    return false;

                #endregion


                #region Perform Online Tasks
                
                
                if (!SingleTvEpisodeItemUpdaterHelpers.PerfrormOnlineTasks
                    (fileServerChecked, fileServerIsOnline, 
                    connectionresult, mdfSettingsb, iBaseSystem, tvdb,
                    currentItem, location,
                    isMultipart, multipart, item, isUNC,
                    seriesID, parentDir))
                    return false;

                if (Helpers.UserCancels(MainImportingEngine.SpecialStatus, item))
                    return false;

                #endregion



                SingleTvEpisodeItemUpdaterHelpers.SetProccesedFlag(item);

                SingleTvEpisodeItemUpdaterHelpers.ProceedToNextItem(ref currentItem, item);
            

            }
            catch (Exception e)
            {     
                SingleTvEpisodeItemUpdaterHelpers.LogException(e, item);
            }


            return true;
    
         
        
        }
 public IList<ITVDBUpdate> GetUpdates(TVDBLib.TimeConstraintEnum timeConstraint)
 {
   try
   {
     return this._db.GetUpdates(timeConstraint);
   }
   catch (Exception ex)
   {
     throw ex;
   }
 }