using System;
using System.Collections.Generic;

using System.Text;
using System.Xml.XPath;
using System.Xml;

namespace StarTrinity
{
	public class DistributedProxySettings
	{
		const string settingsFileName = "StarTrinity.DistributedProxy.settings.xml";
		public static string FullSettingsFileName
		{
			get
			{
				return System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), settingsFileName);
			}
		}

		public static string BaseDirectory
		{
			get
			{
				Uri dllURI = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
				return System.IO.Path.GetDirectoryName(dllURI.LocalPath);
			}
		}
		static XmlDocument Load()
		{
			var fullSettingsFileName = FullSettingsFileName;

            var r = new XmlDocument();

            if (!System.IO.File.Exists(fullSettingsFileName))
            {
                r.LoadXml("<settings></settings>");
            }
            else
            {
                r.Load(fullSettingsFileName);
            }
            return r;
		}
		readonly XmlDocument xml;
		public DistributedProxySettings()
		{
			xml = Load();
		}
		public void SaveToFile()
		{
			xml.Save(FullSettingsFileName);
		}
		public enum Names
		{
			CentralProxyAddress,
			CentralProxyPort,
			Email, // from users_accounts_nodes table
			Password, // from users_accounts_nodes table
            PasswordIsSet,
            InstallationDate
		}
		public string GetSettingValue(Names name, string defaultValue)
		{
			var element = xml.SelectSingleNode("/settings/" + name.ToString());
			if (element != null)
				return (string)element.InnerText;
			else
			{
                var newElement = xml.CreateElement(name.ToString());
                newElement.InnerText = defaultValue;
				xml.SelectSingleNode("/settings").AppendChild(newElement);
				SaveToFile();
				return defaultValue;
			}
		}
		public void SetSettingValue(Names name, string value)
		{
            var element = xml.SelectSingleNode("/settings/" + name.ToString());
			if (element != null)
                element.InnerText = value;
			else
			{
                var newElement = xml.CreateElement(name.ToString());
                newElement.InnerText = value;
                xml.SelectSingleNode("/settings").AppendChild(newElement);
			}
			SaveToFile();
		}
		public int GetSettingValue(Names name, int defaultValue)
		{
			var r = GetSettingValue(name, defaultValue.ToString());
			return Int32.Parse(r);
		}
	}
}
