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

namespace VICrawlerNS
{
	static class Config
	{
		static Dictionary<string, object> m_Data = new Dictionary<string, object>();

		static Random m_Random = new Random();

		public static void Init()
		{
			m_Data.Add("account", "");
			m_Data.Add("sub-account", "");
			m_Data.Add("check-time", 5);
			m_Data.Add("buy-price", 1000000);

			Load();
		}

		static void Load()
		{
			string strPath = Util.GetConfigPath()+"/config.ini";
			if(File.Exists(strPath) == false)
				return;

			string[] aLines = File.ReadAllLines(strPath);
			foreach(string strLine in aLines)
			{
				if(strLine.Trim().Length <= 0)
					continue;

				string[] aTokens = strLine.Trim().Split('=');
				if(aTokens.Length < 2)
					continue;

				if(m_Data.ContainsKey(aTokens[0]) == true)
					m_Data[aTokens[0]] = Convert.ChangeType(aTokens[1], m_Data[aTokens[0]].GetType());
				else
					m_Data.Add(aTokens[0], aTokens[1]);
			}
		}

		static void Save()
		{
			string strContents = "";
			foreach(KeyValuePair<string, object> pair in m_Data)
				strContents += pair.Key + "=" + pair.Value.ToString() + Environment.NewLine;

			string strPath = Util.GetConfigPath()+"/config.ini";
			File.WriteAllText(strPath, strContents, new UTF8Encoding(true));
		}

		public static void SetAccount(string strAccount, string strAccountSub)
		{
			if(strAccount != null)
				m_Data["account"] = strAccount;
			m_Data["sub-account"] = strAccountSub;
			Save();
		}

		public static string GetAccount()
		{
			return (string)m_Data["account"];
		}

		public static string GetSubAccount()
		{
			return (string)m_Data["sub-account"];
		}

		public static void SetCheckTime(int iCheckTime)
		{
			m_Data["check-time"] = iCheckTime;
			Save();
		}

		public static int GetCheckTime()
		{
			return (int)m_Data["check-time"];
		}

		public static void SetBuyPrice(int iPrice)
		{
			m_Data["buy-price"] = iPrice;
			Save();
		}

		public static int GetBuyPrice()
		{
			return (int)m_Data["buy-price"];
		}
	}
}
