using System;
using System.IO;
using System.Linq;

namespace PlayFab
{
    internal class Config
    {
        public static string DataFolder = Path.Combine(Environment.GetEnvironmentVariable("APPDATA"), "PremiumPackInstaller");
        public static string ConfigFile = Path.Combine(DataFolder, "playfab.conf");

        private static void initConfig()
        {
            Directory.CreateDirectory(DataFolder);
            File.WriteAllText(ConfigFile, "");
        }

        private static void replaceConfValue(string key, string newval)
        {
            if (!File.Exists(ConfigFile))
                initConfig();

            string[] keyValuePairs = File.ReadAllLines(ConfigFile);
            for (int i = 0; i < keyValuePairs.Length; i++)
            {
                string[] kvp = keyValuePairs[i].Split(':');
                if (kvp[0] == key)
                    keyValuePairs[i] = key + ":" + newval;
            }

            File.WriteAllLines(ConfigFile, keyValuePairs);
        }

        public static string GetConfValue(string key)
        {
            if (!File.Exists(ConfigFile))
                initConfig();

            string[] keyValuePairs = File.ReadAllLines(ConfigFile);
            foreach (string keyValuePair in keyValuePairs)
            {
                string[] kvp = keyValuePair.Split(':');
                if (kvp[0] == key)
                    return String.Join(":", kvp.Skip(1).ToArray());
            }

            return null;
        }
        public static void WriteConfValue(string key, string value)
        {
            if (!File.Exists(ConfigFile))
                initConfig();
            string curConfValue = GetConfValue(key);

            if (curConfValue == value)
                return;

            if (curConfValue != null)
                replaceConfValue(key, value);
            else
                File.AppendAllLines(ConfigFile, new string[] { key + ":" + value });
        }

    }
}
