using System;
using QCGM;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace QCGM
{
	public class InvalidViewModeException: ApplicationException
	{
		public InvalidViewModeException()
		{
		}

		public InvalidViewModeException(string message): base(message)
		{
		}

		public InvalidViewModeException(string message, Exception inner) : base(message, inner)
		{
		}
	}

	/// <summary>
	/// Summary description for Settings.
	/// </summary>
	[Serializable]
	public class Settings
	{
		public const string DefaultServerName = "Quoridor Classic Game Server";
		public const int DefaultServerPort = 8167;
		public const string DefaultPlayer1Name = "Player 1";
		public const string DefaultPlayer2Name = "Player 2";

		public bool ShowStartupSplash=true;
		public bool UseTimeLimit=true;
		public int TimeLimit=120;
		
		public int ServerListenPort=DefaultServerPort;
		public string ServerName=DefaultServerName;
		
		public string Player1Name=DefaultPlayer1Name;
		public string Player2Name=DefaultPlayer2Name;
				
		public void Fallback()
		{
			ShowStartupSplash=true;
		
			ServerListenPort=DefaultServerPort;
			ServerName=DefaultServerName;
		
			Player1Name=DefaultPlayer1Name;
			Player2Name=DefaultPlayer2Name;
		}
		
		public Settings(string filename)
		{
			Load(filename);
		}

		public bool SaveAs(string filename)
		{
			try
			{
				Stream ostream;
				ostream = File.OpenWrite(filename);

				IFormatter formatter = new BinaryFormatter();
				formatter.Serialize(ostream, ShowStartupSplash);
				formatter.Serialize(ostream, ServerListenPort);
				formatter.Serialize(ostream, ServerName);
				formatter.Serialize(ostream, Player1Name);
				formatter.Serialize(ostream, Player2Name);
				formatter.Serialize(ostream, UseTimeLimit);
				formatter.Serialize(ostream, TimeLimit);

				ostream.Close();
				return true;
			}
			catch(Exception)
			{
				return false;
			}
		}

		private void Load(string filename)
		{
			try
			{
				Stream istream = File.OpenRead(filename);

				if(istream != null)
				{
					IFormatter formatter = new BinaryFormatter();
					ShowStartupSplash = (bool)formatter.Deserialize(istream);
					ServerListenPort = (int)formatter.Deserialize(istream);
					ServerName = (string)formatter.Deserialize(istream);
					Player1Name = (string)formatter.Deserialize(istream);
					Player2Name = (string)formatter.Deserialize(istream);
					UseTimeLimit = (bool)formatter.Deserialize(istream);
					TimeLimit = (int)formatter.Deserialize(istream);
					istream.Close();
					return;
				}
				else
				{
					Fallback();
				}
			}
			catch(Exception)
			{
				Fallback();
			}
		}
	}
}
