using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;

namespace StarTrinity
{
	class Settings
	{
		const string settingsFileName = "StarTrinity.CentralProxy.settings.xml";
		public static string FullSettingsFileName
		{
			get
			{
				return System.IO.Path.Combine(BaseDirectory, settingsFileName);
			}
		}

		public static string BaseDirectory
		{
			get
			{
				Uri dllURI = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
				return System.IO.Path.GetDirectoryName(dllURI.LocalPath);
			}
		}
		static XDocument Load()
		{
			var fullSettingsFileName = FullSettingsFileName;
			if (!System.IO.File.Exists(fullSettingsFileName))
				return XDocument.Parse("<settings></settings>");			
			return XDocument.Load(fullSettingsFileName);
		}
		readonly XDocument xml;
		public Settings()
		{
			xml = Load();
		}
		public void SaveToFile()
		{
			xml.Save(FullSettingsFileName);
		}
		public enum Names
		{
			PortForDp,
			MySqlConnection,
			LogPath,
			MinLocalPortForBrowsers
		}
		public string GetSettingValue(Names name, string defaultValue)
		{
			var element = xml.XPathSelectElement("/settings/" + name.ToString());
			if (element != null)
				return (string)element.Value;
			else
			{
				xml.XPathSelectElement("/settings").Add(new XElement(name.ToString(), defaultValue));
				SaveToFile();
				return defaultValue;
			}
		}
		public int GetSettingValue(Names name, int defaultValue)
		{
			var r = GetSettingValue(name, defaultValue.ToString());
			return Int32.Parse(r);
		}
	}
}
