using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using BankTVUpdater.Consts;
using BankTVUpdater.Logger;
using BankTVUpdater.Helpers.Service;
using BankTVUpdater.Exceptions;
using BankTVUpdater.Model.Service;
using BankTVUpdater.Helpers.BottomBarNews;
using BankTVUpdater.AppUpdaterService;
using BankTVUpdater.Helpers.Config.Local;

namespace BankTVUpdater.Helpers
{
    class UpdateHelper
    {
        public static bool UpdateApp()
        {
            try
            {
                MyLogger.Log("App update started...");
                ServiceHelper service = new ServiceHelper();
                MyLogger.Log("Sprawdzanie zgodności wersji aktualizatora...");
                if (UpdateHelper.CheckUpdaterUpdateNeeded(service))
                {
                    MyLogger.Log("App updater update needed...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Updating currencies...");
                if (!UpdateHelper.StoreCurrencyConfiguration(service))
                {
                    MyLogger.Log("Currencies update failed...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Updating weather icons...");
                List<WeatherIcon> weatherIcons = service.GetWeatherIcons();
                if (weatherIcons == null)
                {
                    MyLogger.Log("Updating weather icons failed...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                foreach (WeatherIcon icon in weatherIcons)
                {
                    FilesHelper.DownloadWeatherIcon(icon);
                }   //for                
                MyLogger.Log("Checking app version...");
                if (!UpdateHelper.CheckAppUpdateNeeded(service))
                {
                    MyLogger.Log("App version OK...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Getting new app configuration...");
                if (!UpdateHelper.StoreAppConfiguration(service))
                {
                    MyLogger.Log("Getting new app configuration failed...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Getting new app configuration for departments...");
                if (!UpdateHelper.StoreAppConfigurationForDepartments(service))
                {
                    MyLogger.Log("Getting new app configuration for departments failed...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Getting bottom bar news...");
                if (!UpdateHelper.StoreBottomBarNewsConfiguration(service))
                {
                    MyLogger.Log("Getting bottom bar news failed...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Getting image files...");
                List<SingleFile> images = service.GetImageFiles();
                if (images == null)
                {
                    images = new List<SingleFile>();
                }   //if
                MyLogger.Log("Getting video files...");
                List<SingleFile> videos = service.GetVideoFiles();
                if (videos == null)
                {
                    videos = new List<SingleFile>();
                }   //if
                MyLogger.Log("Getting news files...");
                List<SingleNews> news = service.GetNewsFiles();
                if (news == null)
                {
                    news = new List<SingleNews>();
                }   //if
                MyLogger.Log("Getting flash files...");
                List<SingleFile> flash = service.GetFlashFiles();
                if (flash == null)
                {
                    flash = new List<SingleFile>();
                }   //if
                MyLogger.Log("Downloading image files...");
                foreach (SingleFile image in images)
                {
                    FilesHelper.DownloadImageFile(image);
                }   //for                
                MyLogger.Log("Downloading video files...");
                foreach (SingleFile video in videos)
                {
                    FilesHelper.DownloadVideoFile(video);
                }   //for                
                MyLogger.Log("Downloading news files...");
                foreach (SingleNews singleNews in news)
                {
                    FilesHelper.DownloadNewsFile(singleNews);
                }   //for
                MyLogger.Log("Downloading flash files...");
                foreach (SingleFile singleFlash in flash)
                {
                    FilesHelper.DownloadFlashFile(singleFlash);
                }   //for
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                MyLogger.Log("App update finished...");
                return false;
            }   //catch
            MyLogger.Log("App update finished...");
            return true;
        }

        public static bool UpdateAppNoMovies()
        {
            try
            {
                MyLogger.Log("App update started no movies...");
                ServiceHelper service = new ServiceHelper();
                MyLogger.Log("Sprawdzanie zgodności wersji aktualizatora...");
                if (UpdateHelper.CheckUpdaterUpdateNeeded(service))
                {
                    MyLogger.Log("App updater update needed...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Updating currencies...");
                if (!UpdateHelper.StoreCurrencyConfiguration(service, false))
                {
                    MyLogger.Log("Currencies update failed...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Checking app version...");
                if (!UpdateHelper.CheckAppUpdateNeeded(service))
                {
                    MyLogger.Log("App version OK...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Getting new app configuration...");
                if (!UpdateHelper.StoreAppConfiguration(service))
                {
                    MyLogger.Log("Getting new app configuration failed...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Getting bottom bar news...");
                if (!UpdateHelper.StoreBottomBarNewsConfiguration(service))
                {
                    MyLogger.Log("Getting bottom bar news failed...");
                    MyLogger.Log("App update finished...");
                    return true;
                }   //if
                MyLogger.Log("Getting image files...");
                List<SingleFile> images = service.GetImageFiles();
                if (images == null)
                {
                    images = new List<SingleFile>();
                }   //if
                MyLogger.Log("Getting news files...");
                List<SingleNews> news = service.GetNewsFiles();
                if (news == null)
                {
                    news = new List<SingleNews>();
                }   //if
                MyLogger.Log("Getting flash files...");
                List<SingleFile> flash = service.GetFlashFiles();
                if (flash == null)
                {
                    flash = new List<SingleFile>();
                }   //if
                MyLogger.Log("Downloading image files...");
                foreach (SingleFile image in images)
                {
                    FilesHelper.DownloadImageFile(image, false);
                }   //for                
                MyLogger.Log("Downloading news files...");
                foreach (SingleNews singleNews in news)
                {
                    FilesHelper.DownloadNewsFile(singleNews, false);
                }   //for
                MyLogger.Log("Downloading flash files...");
                foreach (SingleFile singleFlash in flash)
                {
                    FilesHelper.DownloadFlashFile(singleFlash, false);
                }   //for
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                MyLogger.Log("App update no movies finished...");
                return false;
            }   //catch
            MyLogger.Log("App update no movies finished...");
            return true;
        }

        private static bool CheckUpdaterUpdateNeeded(ServiceHelper service)
        {
            if (service == null)
            {
                return true;
            }   //if
            try
            {
                if (service.IsUpdaterUpdateNeeded(GlobalConsts.UPDATER_VERSION))
                {
                    return true;
                }   //if
                return false;
            }   //try
            catch (UpdaterConnectionException ex)
            {
                MyLogger.Log(ex);
                return true;
            }
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                return true;
            }
        }

        private static bool CheckAppUpdateNeeded(ServiceHelper service)
        {
            if (service == null)
            {
                return true;
            }   //if
            try
            {
                bool result = service.IsAppUpdateNeeded();
                return result;
            }   //try
            catch (UpdaterConnectionException ex)
            {
                MyLogger.Log(ex);
                return true;
            }
            catch (Exception ex)
            {
                MyLogger.Log(ex);                
                return true;
            }
        }

        private static bool StoreAppConfiguration(ServiceHelper service)
        {
            if (service == null)
            {                
                return false;
            }   //if
            try
            {
                string appConfigFolder = GlobalHelper.GetUserAppDataFolder();
                if (String.IsNullOrEmpty(appConfigFolder))
                {
                    return false;
                }   //if
                string xmlConfig = service.GetAppConfiguration();
                if (String.IsNullOrEmpty(xmlConfig))
                {
                    return false;
                }   //if
                string appConfigFile = System.IO.Path.Combine(appConfigFolder, GlobalConsts.APP_CONFIG_FILE);
                if (File.Exists(appConfigFile))
                {
                    File.Delete(appConfigFile);
                }   //if                
                File.WriteAllText(appConfigFile, xmlConfig);
                return true;
            }   //try
            catch (UpdaterConnectionException ex)
            {
                MyLogger.Log(ex);
                return false;
            }
            catch (Exception ex)
            {
                MyLogger.Log(ex);                
                return false;
            }   //catch
        }

        private static bool StoreCurrencyConfiguration(ServiceHelper service, bool overrideFiles = true)
        {
            if (service == null)
            {                
                return false;
            }   //if
            try
            {
                string currencyConfigFolder = GlobalHelper.GetCurrencyFolder();
                if (String.IsNullOrEmpty(currencyConfigFolder))
                {
                    return false;
                }   //if
                string currencyConfig = service.GetCurrencyConfiguration();
                if (String.IsNullOrEmpty(currencyConfig))
                {
                    return false;
                }   //if
                string currencyConfigFile = System.IO.Path.Combine(currencyConfigFolder, GlobalConsts.CURRENCY_CONFIG_FILE);
                if (File.Exists(currencyConfigFile))
                {
                    File.Delete(currencyConfigFile);
                }   //if                
                File.WriteAllText(currencyConfigFile, currencyConfig);
                List<CurrencyItem> currencyFiles = service.GetCurrencyFiles();
                if (currencyFiles == null)
                {
                    return false;
                }   //if
                if (currencyFiles.Count > 0)
                {
                    int progressInterval = 100 / currencyFiles.Count;
                    foreach (CurrencyItem currencyFile in currencyFiles)
                    {
                        FilesHelper.DownloadCurrencyImage(currencyFile, overrideFiles);
                    }   //for
                }   //if
                return true;
            }   //try
            catch (UpdaterConnectionException ex)
            {
                MyLogger.Log(ex);
                return false;
            }
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                return false;
            }   //catch
        }

        private static bool StoreBottomBarNewsConfiguration(ServiceHelper service)
        {
            if (service == null)
            {
                return false;
            }   //if
            try
            {
                string bottomBarNewsFolder = GlobalHelper.GetBottomBarNewsFolder();
                if (String.IsNullOrEmpty(bottomBarNewsFolder))
                {
                    return false;
                }   //if
                List<string> bottomBarNews = service.GetBottomBarNews();
                if (bottomBarNews == null)
                {
                    bottomBarNews = new List<string>();
                }   //if
                string bottomBarNewsFile = System.IO.Path.Combine(bottomBarNewsFolder, GlobalConsts.BOTTOM_BAR_NEWS_FILE);
                if (File.Exists(bottomBarNewsFile))
                {
                    File.Delete(bottomBarNewsFile);
                }   //if                
                BottomBarNewsXmlHelper.SetBottomBarNews(bottomBarNews);
                return true;
            }   //try
            catch (UpdaterConnectionException ex)
            {
                MyLogger.Log(ex);
                return false;
            }
            catch (Exception ex)
            {
                MyLogger.Log(ex);                
                return false;
            }   //catch
        }

        private static bool StoreAppConfigurationForDepartments(ServiceHelper service)
        {
            if (service == null)
            {
                return false;
            }   //if
            try
            {
                string appConfigFolder = GlobalHelper.GetUserAppDataFolder();
                if (String.IsNullOrEmpty(appConfigFolder))
                {
                    return false;
                }   //if
                Departments departments = service.GetDepartments();
                if (departments == null)
                {
                    return false;
                }   //if
                List<Department> configDepartments = FilesHelper.ConvertWSDepartmentsToList(departments);
                if (configDepartments == null)
                {
                    return false;
                }   //if
                if (configDepartments.Count > 0)
                {
                    foreach (Department department in configDepartments)
                    {
                        string xmlConfig = service.GetAppConfigurationForDepartments(department.Parameter);
                        if (String.IsNullOrEmpty(xmlConfig))
                        {
                            return false;
                        }   //if
                        string appConfigFile = System.IO.Path.Combine(appConfigFolder, String.Format("{0}-{1}{2}", GlobalConsts.APP_CONFIG_FILE_PREFIX, department.GetFormattedParameter(), GlobalConsts.APP_CONFIG_FILE_SUFFIX));
                        if (File.Exists(appConfigFile))
                        {
                            File.Delete(appConfigFile);
                        }   //if                
                        XmlLocalConfigHelper.SetLocalConfigObject(department.City, department.GetFormattedParameter());
                        File.WriteAllText(appConfigFile, xmlConfig);
                    }   //for
                }   //if
                return true;
            }   //try
            catch (UpdaterConnectionException ex)
            {
                return false;
            }
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                return false;
            }   //catch
        }

    }

}
