using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices.WindowsRuntime;

namespace FiscalPrinterSDK
{
    public static class SDKSettings
    {
        public static Dictionary<string, string> mSettings = new Dictionary<string, string>();

        public static void Load(string fileName)
        {
            if (!File.Exists(fileName)) return;
            var settingsList = File.ReadAllLines(fileName);
            if (settingsList.Length < 1) return;
            for (int i = 0; i < settingsList.Length; i++)
            {
                if (!String.IsNullOrEmpty(settingsList[i]))
                {
                    var splitRow = settingsList[i].Split('=');
                    mSettings[splitRow[0]] = splitRow[1];
                }
            }
        }

        public static void Save()
        {
            StringBuilder sb = new StringBuilder();
            string filePath = "";
            foreach (var k in mSettings)
            {
                sb.AppendLine(k.Key + "=" + k.Value);
            }
            //if (!System.Runtime.InteropServices.WindowsRuntime.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            //{
            //    filePath = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            // }
            //else
            //{
            //    filePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\" + "FiscalPrinterSDK_BGR";
            //    if (!Directory.Exists(filePath))
            //    {
            //        var r = Directory.CreateDirectory(filePath);
            //        if (!LogComm.HasWriteAccessToFolder(filePath)) return;
            //    }
            //}
            var fullPath = filePath + "\\" + "settings.txt";
            File.WriteAllText(fullPath, sb.ToString());
        }

        public static string GetString(string settingName, string defaultValue)
        {
            if (mSettings.ContainsKey(settingName)) return mSettings[settingName];
            else return defaultValue;
        }

        public static bool GetBool(string settingName, bool defaultValue)
        {
            if (mSettings.ContainsKey(settingName)) return true;
            else return defaultValue;
        }
        public static int GetInt(string settingName, int defaultValue)
        {
            string value = "";
            bool keyExists = mSettings.TryGetValue(settingName, out value);
            if (keyExists) return int.Parse(value);
            else return defaultValue;
        }

        public static void SetSetting(string settingName, string settingValue)
        {
            //mSettings.Add(settingName,settingValue);
            mSettings[settingName] = settingValue;
        }
    }
}
