using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using Mox.SharpDX.Renderer;
using Mox.Shared;
using SharpDX.Windows;

namespace Mox.SharpDX
{
	internal class Program : ProgramBase
	{
		[STAThread]
		public static void Main()
		{
			Application.SetCompatibleTextRenderingDefault(false);
			IOHelper.GetText = _sPath => Task.FromResult(File.ReadAllText("bridge/" + _sPath));
			IOHelper.GetBytes = _sPath => Task.FromResult(File.ReadAllBytes("bridge/" + _sPath));
			var program = new Program();
			program.Run();
		}

		private async void Run()
		{
			var renderForm = new RenderForm("Mox")
			{
				ClientSize = new Size(c_iClientWidth, c_iClientHeight),
				StartPosition = FormStartPosition.CenterScreen,
				FormBorderStyle = FormBorderStyle.None,
				IsFullscreen = false
			};

			Renderer = new DirectXRenderer(renderForm);

			renderForm.KeyPress += (_sender, _args) =>
			{
				if (s_dKeyCodes.TryGetValue(_args.KeyChar, out var eKey))
				{
					GameLoop.OnKeyPressed(eKey);
				}
				else if (_args.KeyChar == 27)
				{
					renderForm.Close();
				}
			};

			renderForm.MouseDown += (_sender, _args) =>
			{
				OnMouseDown(_args.X, _args.Y);
			};

			renderForm.MouseMove += (_sender, _args) =>
			{
				OnMouseMoved(_args.X, _args.Y);
			};

			renderForm.MouseUp += (_sender, _args) =>
			{
				OnMouseUp(_args.X, _args.Y);
			};

			await GameLoop.Init();
            Init();

			var stopwatch = new Stopwatch();
			stopwatch.Start();
			RenderLoop.Run(renderForm, () =>
			{
				var delta = stopwatch.Elapsed.TotalSeconds;
				stopwatch.Restart();
                Update(delta);
            });

			Renderer.Dispose();
		}

		public override Task RegisterSound(string _sSoundId, string _sPath)
		{
			m_dSounds[_sSoundId] = new Sound(_sSoundId, _sPath);

			return Task.FromResult(default(object));
		}

		public override void ShowMessage(string _sMessage)
		{
			MessageBox.Show(_sMessage);
		}

		public override bool GetData(string _sKey, out string _sData)
		{
			var sPath = Path.Combine(
				Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
				"HexTowerDefense", 
				_sKey + ".txt");

			if (File.Exists(sPath))
			{
				_sData = File.ReadAllText(sPath);
				return true;
			}

			_sData = null;
			return false;
		}

		public override void SetData(string _sKey, string _sData)
		{
			var sPath = Path.Combine(
				Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
				"HexTowerDefense", 
				_sKey + ".txt");

			if (_sData == null)
			{
				if (File.Exists(sPath))
				{
					File.Delete(sPath);
				}
			}
			else
			{
				Directory.CreateDirectory(Path.GetDirectoryName(sPath));
				using (var stream = new FileStream(sPath, FileMode.Create))
				{
					using (var writer = new StreamWriter(stream))
					{
						writer.WriteLine(_sData);
					}
				}
			}
		}
	}
}
