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

namespace SmartAquaViewer.INI
{
    class INIManager
    {
        private readonly string strINIPath;

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        private static extern long WritePrivateProfileString(
        string section, string key, string val, string filePath);

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        private static extern int GetPrivateProfileString(
            string section, string key, string def, StringBuilder retVal, int size, string filePath);

        public INIManager(String INIPath)
        {
            strINIPath = INIPath;
            if (!ExistINI())
            {
                CreateIni();
            }
            else
            {
                CheckAndInsertIni();
            }
        }

        public void CreateIni()
        {
            WriteValue("CONFIG", Constants.Config.TITLE, "SmartAquaViwer");
            WriteValue("CONFIG", Constants.Config.DATA_FILE_PATH, Constants.Directories.DATA_FOLDER);
        }

        public bool ExistINI()
        {
            return File.Exists(strINIPath);
        }

        public void CheckAndInsertIni()
        {
            CheckAndInsert("CONFIG", Constants.Config.TITLE, "SmartAquaViwer");
            CheckAndInsert("CONFIG", Constants.Config.DATA_FILE_PATH, Constants.Directories.DATA_FOLDER);

        }

        public void CheckAndInsert(String strSection, String strKey, String strValue)
        {
            string key = ReadValue(strSection, strKey);
            if (key == null || key.Trim() == "")
            {
                WriteValue(strSection, strKey, strValue);
            }
        }

        public void WriteValue(String strSection, String strKey, String strValue)
        {
            WritePrivateProfileString(strSection, strKey, strValue, strINIPath);
        }

        public void DeleteSection(String strSection)
        {
            WritePrivateProfileString(strSection, null, null, strINIPath);
        }

        public string ReadValue(String strSection, String Key)
        {
            return ReadValue(strSection, Key, "");
        }

        public string ReadValue(String strSection, String Key, String def)
        {
            var strValue = new StringBuilder(255);

            int i = GetPrivateProfileString(strSection, Key, def, strValue, 255, strINIPath);

            return strValue.ToString();
        }
    }
}
