// Copyright © 2017-2018 Atomic Software, LLC. All Rights Reserved.
// See LICENSE.md for full license information.

using Atom.Core.Diagnostics;
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Atom.Core.IO
{
    public class ConfigurationFile
    {
        private readonly string Path;

        public ConfigurationFile(string path)
        {
            Path = path;
        }

        public void SetValue(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value, Path);
        }

        private string GetValue(string section, string key)
        {
            var Builder = new StringBuilder(255);

            GetPrivateProfileString(section, key, "", Builder, 255, Path);

            var ReturnValue = Builder.ToString();

            if (string.IsNullOrEmpty(ReturnValue))
            {
                Log.Warning($"Config key '{key}' not found.");
            }

            return ReturnValue;
        }

        public string GetString(string section, string key)
        {
            return GetValue(section, key);
        }

        public byte GetByte(string section, string key)
        {
            return Convert.ToByte(GetValue(section, key));
        }

        public short GetInt16(string section, string key)
        {
            return Convert.ToInt16(GetValue(section, key));
        }

        public int GetInt32(string section, string key)
        {
            return Convert.ToInt32(GetValue(section, key));
        }

        public long GetInt64(string section, string key)
        {
            return Convert.ToInt64(GetValue(section, key));
        }

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
    }
}
