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.Forms;

namespace SanSystem.Einstellungen
{
    abstract class Settings : IDisposable
    {
        protected Dictionary<string, int> configuration = new Dictionary<string, int>();

        const string pfad = "Settings";

        string modPath = "";
        public Settings(string module)
        {
            string modname = string.Format("{0}.set", module);

            modPath = Path.Combine(pfad, modname);
            if (!Directory.Exists(pfad)) Directory.CreateDirectory(pfad);
            if(!File.Exists(modPath))
            {
                InitDevValues();
                SaveSettings();
            }
            else
            {
                string input = File.ReadAllText(modPath);
                configuration = (Dictionary<string, int>)JsonConvert.DeserializeObject(input, typeof(Dictionary<string, int>));
            }
        }

        protected int getConfiguration(string keyName, int retry = 0)
        {
            if (retry >= 3)
                throw new Exception("Fehler, zuviele versuche");
            int result = -1;
            if(!configuration.TryGetValue(keyName,out result))
            {
                configuration.Add(keyName, 20);
                //return -1;
                result = getConfiguration(keyName,retry++);
                SaveSettings();
                return result;
            }
            else
            {
                return result;
            }
        }

        protected void setConfig(string keyName, int value)
        {
            configuration[keyName] = value;
        }

        public abstract void InitDevValues();
        public abstract int GetWidth(DataGridViewColumn dataGridViewColumn);
        public abstract void SetWidth(DataGridViewColumn dataGridViewColumn);

        public virtual void SaveSettings()
        {
            string ser = JsonConvert.SerializeObject(configuration);
            File.WriteAllText(modPath, ser);
        }

        public void Dispose()
        {
            SaveSettings();
        }
    }
}
