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.Exceptions;
using System.Windows;
using BankTVUpdater.AppUpdaterService;
using System.Xml;
using System.Net;
using BankTVUpdater.Model.Service;
using BankTVUpdater.Config;
using System.Xml.Serialization;

namespace BankTVUpdater.Helpers.Config
{
    class XmlConfigHelper
    {

        private static configuration GetConfigObject()
        {
            try 
            {
                XmlSerializer serializer = new XmlSerializer(typeof(configuration));
                string appConfigFolder = GlobalHelper.GetUserAppDataFolder();
                if (String.IsNullOrEmpty(appConfigFolder))
                {
                    throw new AppNotInitiatedException("Unable to get app config folder.");
                }   //if
                string appConfigFile = System.IO.Path.Combine(appConfigFolder, GlobalConsts.APP_CONFIG_FILE);
                if (!File.Exists(appConfigFile))
                {
                    throw new AppNotInitiatedException("Unable to get app config folder.");
                }   //if
                TextReader reader = new StreamReader(appConfigFile);
                try
                {
                    return (configuration)serializer.Deserialize(reader);
                }   //try
                finally
                {
                    reader.Close();
                }   //finally
            }   //try
            catch (AppNotInitiatedException)
            {
                throw;
            }   //catch
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                MyLogger.Log(ex.GetBaseException());
                return null;
            }   //catch
        }

        public static int GetCurrentVersion()
        {
            try
            {
                configuration xmlConfig = XmlConfigHelper.GetConfigObject();
                return xmlConfig.version;
            }
            catch (AppNotInitiatedException)
            {
                return 0;
            }   //catch
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                throw;
            }
        }

    }

}
