using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ZKuP
{
    public static class Settings
    {
        static Dictionary<string, object> SettingsDict = new Dictionary<string, object>();

        //

        //static string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuPSettings.json";


        private static void LoadSettings()
        {
            //if (!File.Exists(path)) File.Create(path);
            //var assets = AvaloniaLocator.Current.GetService<IAssetLoader>();

            //while(Helper.IsFileLocked(new FileInfo(path)).Value) { }

            //var json = File.ReadAllText((path), Encoding.UTF8);
            var json = SQL.ReadSingleValue($"SELECT Settings FROM {MainWindow.table}.userSettings WHERE User = '{Environment.UserName}'");
            SettingsDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

            if(SettingsDict  == null) SettingsDict = new Dictionary<string, object>();
        }

        public static object GetSetting(string key)
        {
            if (SettingsDict == null || SettingsDict.Count == 0) LoadSettings();


            if (SettingsDict.ContainsKey(key))
            {
                if (SettingsDict[key].GetType() == typeof(long))
                    return (int)(long)SettingsDict[key];
                else
                    return SettingsDict[key];

            }
            else return "";
        }

        public static double GetSettingDouble(string key)
        {
            if (SettingsDict == null || SettingsDict.Count == 0) LoadSettings();


            if (SettingsDict.ContainsKey(key))
            {
                var value = SettingsDict[key];
                return (double)value;
            }
            return 0;
        }

        public static int GetSettingInt(string key)
        {
            if (SettingsDict == null || SettingsDict.Count == 0) LoadSettings();


            if (SettingsDict.ContainsKey(key))
            {
                var value = (long)SettingsDict[key];
                return Convert.ToInt32(value);
            }
            return 0;
        }

        public static string GetSettingString(string key)
        {
            if (SettingsDict == null || SettingsDict.Count == 0) LoadSettings();


            if (SettingsDict.ContainsKey(key))
            {
                var value = SettingsDict[key];
                return value.ToString();
            }
            return "";
        }

        public static DateTime GetSettingDateTime(string key)
        {
            if (SettingsDict == null || SettingsDict.Count == 0) LoadSettings();


            if (SettingsDict.ContainsKey(key))
            {
                var value = SettingsDict[key];
                return Convert.ToDateTime(value.ToString());
            }
            return DateTime.Now;
        }

        public static TimeSpan GetSettingTimeSpan(string key)
        {
            if (SettingsDict == null || SettingsDict.Count == 0) LoadSettings();


            if (SettingsDict.ContainsKey(key))
            {
                var value = SettingsDict[key];
                return TimeSpan.Parse(value.ToString());
            }
            return new TimeSpan();
        }

        public static bool GetSettingBool(string key)
        {
            if (SettingsDict == null || SettingsDict.Count == 0) LoadSettings();


            if (SettingsDict.ContainsKey(key))
            {
                var value = SettingsDict[key];
                return Convert.ToBoolean(value);
            }
            return false;
        }


        public static bool? GetSettingButtonState(string key)
        {
            if (SettingsDict == null || SettingsDict.Count == 0) LoadSettings();


            if (SettingsDict.ContainsKey(key))
            {
                var value = SettingsDict[key];
                if (value != null) return Convert.ToBoolean(value);
                else return null;
            }
            return false;
        }
        /// <summary>
        /// Write a Setting to Storage, Creates a new one if not exists
        /// </summary>
        /// <param name="key">Key Value</param>
        /// <param name="setting">Setting Value</param>
        /// <param name="save">Should it be saved after inserting</param>
        public static void WriteSetting(string key, object setting, bool save = false)
        {
            if (SettingsDict == null || SettingsDict.Count == 0) LoadSettings();

            if (SettingsDict.ContainsKey(key))
                SettingsDict[key] = setting;
            else SettingsDict.Add(key, setting);

            if (save) Save();
        }

        public static async void Save()
        {
            //var assets = AvaloniaLocator.Current.GetService<IAssetLoader>();
            var serialized = JsonConvert.SerializeObject(SettingsDict);

            await SQL.CreateAndWriteSQL($"REPLACE INTO {MainWindow.table}.userSettings (User, Settings) VALUES (@user, @settings)", new List<MySql.Data.MySqlClient.MySqlParameter>()
            {
                new MySql.Data.MySqlClient.MySqlParameter("@user", Environment.UserName),
                new MySql.Data.MySqlClient.MySqlParameter("@settings", serialized)
            });

            //while (Helper.IsFileLocked(new FileInfo(path)).Value) { await Task.Delay(2000); }
            //File.WriteAllText(path, serialized);
            //FileHandler.WriteToFileThreadSafe(path, serialized);
        }

    }
}
