using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using BankTV.Consts;
using BankTV.Logger;
using BankTV.Exceptions;
using System.Windows;
using System.Xml;
using System.Net;
using BankTV.Model.Stock;
using BankTV.Stock;
using System.Xml.Serialization;
using System.Globalization;

namespace BankTV.Helpers.Stock
{
    class StockXmlHelper
    {

        private static stock GetStockXmlObject()
        {
            try 
            {
                XmlSerializer serializer = new XmlSerializer(typeof(stock));
                string stockFolder = GlobalHelper.GetStockFolder();
                if (String.IsNullOrEmpty(stockFolder))
                {
                    throw new AppNotInitiatedException("Unable to get stock folder.");
                }   //if
                string stockFile = System.IO.Path.Combine(stockFolder, GlobalConsts.STOCK_CONFIG_FILE);
                if (!File.Exists(stockFile))
                {
                    throw new AppNotInitiatedException("Unable to get stock file.");
                }   //if
                TextReader reader = new StreamReader(stockFile);
                try
                {
                    return (stock)serializer.Deserialize(reader);
                }   //try
                finally
                {
                    reader.Close();
                }   //finally
            }   //try
            catch (AppNotInitiatedException)
            {
                throw;
            }   //catch
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                return null;
            }   //catch
        }

        public static bool SetStockXmlObject(List<Model.Stock.StockItem> stockItems)
        {
            if (stockItems == null)
            {
                return false;
            }   //if
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(stock));
                string stockFolder = GlobalHelper.GetStockFolder();
                if (String.IsNullOrEmpty(stockFolder))
                {
                    throw new AppNotInitiatedException("Unable to get stock folder.");
                }   //if
                string stockFile = System.IO.Path.Combine(stockFolder, GlobalConsts.STOCK_CONFIG_FILE);
                Stream writer = new FileStream(stockFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                try
                {
                    stock stockConfig = new stock();
                    stockItem[] newStockItems = new stockItem[GlobalConsts.STOCK_ACCEPTABLE_NAMES.Count()];
                    int counter = 0;
                    foreach (Model.Stock.StockItem itemToInsert in stockItems)
                    {
                        stockItem newStockItem = new stockItem();
                        newStockItem.closing = itemToInsert.Closing.ToString(CultureInfo.InvariantCulture);
                        newStockItem.entry_date = itemToInsert.EntryDate.ToString(CultureInfo.InvariantCulture);
                        newStockItem.max = itemToInsert.Max.ToString(CultureInfo.InvariantCulture);
                        newStockItem.min = itemToInsert.Min.ToString(CultureInfo.InvariantCulture);
                        newStockItem.opening = itemToInsert.Opening.ToString(CultureInfo.InvariantCulture);
                        newStockItem.trade = itemToInsert.Trade.ToString(CultureInfo.InvariantCulture);
                        newStockItem.name = itemToInsert.Name;
                        newStockItems[counter] = newStockItem;
                        counter++;
                    }   //for
                    stockConfig.Items = newStockItems;
                    serializer.Serialize(writer, stockConfig);
                    writer.Close();
                    return true;
                }   //try
                finally
                {
                    writer.Close();
                }   //finally
            }   //try
            catch (AppNotInitiatedException)
            {
                throw;
            }   //catch
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                return false;
            }   //catch
        }

        private static Model.Stock.StockItem ConvertXmlItemToStockItem(stockItem stockItem)
        {
            if (stockItem == null)
            {
                return null;
            }   //if
            try
            {
                Model.Stock.StockItem newItem = new StockItem();
                newItem.Closing = decimal.Parse(stockItem.closing, CultureInfo.InvariantCulture);
                newItem.EntryDate = DateTime.Parse(stockItem.entry_date, CultureInfo.InvariantCulture);
                newItem.Max = decimal.Parse(stockItem.max, CultureInfo.InvariantCulture);
                newItem.Min = decimal.Parse(stockItem.min, CultureInfo.InvariantCulture);
                newItem.Name = stockItem.name;
                newItem.Opening = decimal.Parse(stockItem.opening, CultureInfo.InvariantCulture);
                newItem.Trade = decimal.Parse(stockItem.trade, CultureInfo.InvariantCulture);
                return newItem;
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                return null;
            }   //catch
        }

        public static List<StockItem> GetCurrentIndexes()
        {
            List<StockItem> stockItems = new List<StockItem>();
            try
            {                
                stock stockConfig = StockXmlHelper.GetStockXmlObject();
                if (stockConfig == null)
                {
                    return stockItems;
                }   //if
                if (stockConfig.Items == null)
                {
                    return stockItems;
                }   //if
                foreach (stockItem xmlItem in stockConfig.Items)
                {
                    StockItem newItem = StockXmlHelper.ConvertXmlItemToStockItem(xmlItem);
                    if (newItem != null)
                    {
                        stockItems.Add(newItem);
                    }   //if
                }   //for
                return stockItems;
            }
            catch (AppNotInitiatedException)
            {
                return new List<StockItem>();
            }   //catch
            catch (Exception ex)
            {
                MyLogger.Log(ex);
                throw;
            }
        }

    }

}
