using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Windows.Storage;
using Windows.Storage.Streams;
using System.IO;
using StockPortfolio.Model;
using System.Collections.ObjectModel;

namespace StockPortfolio
{
    public class LocalStorage
    {

        //private static List<object> _data = new List<object>();

        //public static List<object> Data
        //{
        //    get { return _data; }
        //    set { _data = value; }
        //}
        public static StorageFile file { get; set; }

        private const string filename = "watchlist.xml";

        private const string userFileName = "User.xml";

   
        static async public Task<User> LoadUser<T>()
        {
            if (await DoesFileExistAsync(userFileName))
            {
                //await Windows.System.Threading.ThreadPool.RunAsync((sender) => LocalStorage.LoadAsync<T>().Wait(), Windows.System.Threading.WorkItemPriority.Normal);
                StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(userFileName, CreationCollisionOption.OpenIfExists);
                if (sessionFile == null)
                {
                    return null;
                }
                IInputStream sessionInputStream = await sessionFile.OpenReadAsync();

                User items = new User();
                try
                {
                    XmlSerializer deserializer = new XmlSerializer(typeof(User), new Type[] { typeof(T) });
                    items = (User)deserializer.Deserialize(sessionInputStream.AsStreamForRead());
                    sessionInputStream.Dispose();
                }
                catch { }
                return items;
            }
            else
            {
                file = await ApplicationData.Current.LocalFolder.CreateFileAsync(userFileName);
                return null;
            }
        }
        static async public Task SaveUser<T>(User items)
        {
            if (await DoesFileExistAsync(userFileName))
            {
                await Windows.System.Threading.ThreadPool.RunAsync((sender) => LocalStorage.SaveUserAsync<T>(items).Wait(), Windows.System.Threading.WorkItemPriority.Normal);
            }
            else
            {
                file = await ApplicationData.Current.LocalFolder.CreateFileAsync(userFileName, CreationCollisionOption.ReplaceExisting);
            }
        }

        static async public Task Save<T>(List<StockDataItem> items)
        {
            if (await DoesFileExistAsync(filename))
            {
                await Windows.System.Threading.ThreadPool.RunAsync((sender) => LocalStorage.SaveAsync<T>(items).Wait(), Windows.System.Threading.WorkItemPriority.Normal);
            }
            else
            {
                file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            }
        }

        static async public Task<List<StockDataItem>> Load<T>()
        {
            if (await DoesFileExistAsync(filename))
            {
                //await Windows.System.Threading.ThreadPool.RunAsync((sender) => LocalStorage.LoadAsync<T>().Wait(), Windows.System.Threading.WorkItemPriority.Normal);
                StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
                if (sessionFile == null)
                {
                    return null;
                }
                IInputStream sessionInputStream = await sessionFile.OpenReadAsync();

                List<StockDataItem> items = new List<StockDataItem>();
                try
                {
                    XmlSerializer deserializer = new XmlSerializer(typeof(List<StockDataItem>), new Type[] { typeof(T) });
                    items = (List<StockDataItem>)deserializer.Deserialize(sessionInputStream.AsStreamForRead());
                    sessionInputStream.Dispose();
                }
                catch { }
                return items;
            }
            else
            {
                file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename);
                return null;
            }
        }

        static async Task<bool> DoesFileExistAsync(string fileName)
        {
            try
            {
                await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
                return true;
            }
            catch
            {
                return false;
            }
        }

        static async private Task SaveAsync<T>(List<StockDataItem> items)
        {
            StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            IRandomAccessStream sessionRandomAccess = await sessionFile.OpenAsync(FileAccessMode.ReadWrite);
            IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
            var serializer = new XmlSerializer(typeof(List<StockDataItem>), new Type[] { typeof(T) });

            serializer.Serialize(sessionOutputStream.AsStreamForWrite(), items);
            sessionRandomAccess.Dispose();
            await sessionOutputStream.FlushAsync();
            sessionOutputStream.Dispose();
        }

        static async private Task SaveUserAsync<T>(User items)
        {
            StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(userFileName, CreationCollisionOption.ReplaceExisting);
            IRandomAccessStream sessionRandomAccess = await sessionFile.OpenAsync(FileAccessMode.ReadWrite);
            IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
            var serializer = new XmlSerializer(typeof(User), new Type[] { typeof(T)});

            serializer.Serialize(sessionOutputStream.AsStreamForWrite(), items);
            sessionRandomAccess.Dispose();
            await sessionOutputStream.FlushAsync();
            sessionOutputStream.Dispose();
        }
        static async private Task<List<StockDataItem>> LoadAsync<T>()
        {
            StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
            if (sessionFile == null)
            {
                return null;
            }
            IInputStream sessionInputStream = await sessionFile.OpenReadAsync();

            List<StockDataItem> items = new List<StockDataItem>();
            XmlSerializer deserializer = new XmlSerializer(typeof(List<StockDataItem>), new Type[] { typeof(T) });
            items = (List<StockDataItem>)deserializer.Deserialize(sessionInputStream.AsStreamForRead());
            sessionInputStream.Dispose();

            return items;
        }
    }
}
