using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Windows.Storage;

namespace FoxTube
{
    public class HistoryItem
    {
        public string Id { get; set; }
        public TimeSpan LeftOn { get; set; } = TimeSpan.FromSeconds(0);
    }

    public static class HistorySet
    {
        public static List<HistoryItem> Items { get; set; } = new List<HistoryItem>();

        public static void Update(HistoryItem item)
        {
            if (!SecretsVault.IsAuthorized)
                return;

            Items.RemoveAll(i => i.Id == item.Id);

            Items.Insert(0, item);
            if (Items.Count > 200)
                Items.RemoveRange(200, Items.Count - 200);
            Save();
        }

        public static void Delete(HistoryItem item)
        {
            if (!SecretsVault.IsAuthorized)
                return;

            Items.Remove(item);
            Save();
        }

        public static void Clear()
        {
            if (!SecretsVault.IsAuthorized)
                return;

            Items.Clear();
            Save();
        }

        public static void Save()
        {
            List<HistoryItem>[] parts = new List<HistoryItem>[4]
            {
                new List<HistoryItem>(), new List<HistoryItem>(),
                new List<HistoryItem>(), new List<HistoryItem>()
            };

            foreach(HistoryItem i in Items)
                if (parts[0].Count < 50)
                    parts[0].Add(i);
                else
                {
                    if (parts[1].Count < 50)
                        parts[1].Add(i);
                    else
                    {
                        if (parts[2].Count < 50)
                            parts[2].Add(i);
                        else
                            parts[3].Add(i);
                    }
                }

            for(int k = 0; k < parts.Length; k++)
                ApplicationData.Current.RoamingSettings.Values[$"history-{SecretsVault.AccountId}-level{k}"] = JsonConvert.SerializeObject(parts[k]);
        }

        public static void Load()
        {
            try
            {
                for (int k = 0; k < 4; k++)
                    Items.AddRange(JsonConvert.DeserializeObject<List<HistoryItem>>(ApplicationData.Current.RoamingSettings.Values[$"history-{SecretsVault.AccountId}-level{k}"] as string));
            }
            catch { }
        }
    }
}
