using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using DxLibDLL;
using Nlgp1.B2DX;
using Nlgp1.Characters;
using Nlgp1.Common;
using Nlgp1.Drawers;
using Nlgp1.Sprites;
using Nlgp1.Stages;
using Nlgp1.Utilities;

namespace Nlgp1 {
	public static class Program {
		/// <summary>
		/// フレームレート
		/// </summary>
		private static FrameRate rate = new FrameRate();

		/// <summary>
		/// アプリケーションのメイン エントリ ポイントです。
		/// </summary>
		[STAThread]
		public static void Main( params string[] args ) {
			if( args.Length > 0 ) {
				Program.currentDirectory = Path.GetFullPath( args[ 0 ] );
			}
			else {
				string entryPath = Path.GetDirectoryName( System.Reflection.Assembly.GetEntryAssembly().Location );
				string dataTextPath = Path.Combine( entryPath , "pathSetting.txt" );
				if( !File.Exists( dataTextPath ) ) {
					Program.currentDirectory = entryPath;
				}
				else {
					Program.currentDirectory = Path.GetFullPath( Path.Combine( entryPath , File.ReadAllText( dataTextPath ).Trim() ) );
				}
			}

			DX.SetWindowText( "魔法少女リリカルなのは ????? (開発中)" );
			DX.SetWindowSize( ScreenWidth , ScreenHeight );
			DX.ChangeWindowMode( true );
			DX.SetAlwaysRunFlag( true );
			DX.SetDoubleStartValidFlag( true );

			DX.DxLib_Init();
			Program.actions = new List< Action >();
			Program.font = DX.CreateFontToHandle( "メイリオ" , 24 , -1 , DX.DX_FONTTYPE.ANTIALIASING );
			Screen screen;
			if( args.Length > 1 ) {
				screen = new GameScreen( int.Parse( args[ 1 ] ) );
			}
			else {
				screen = new MenuScreen();
			}
			int baseTime = Environment.TickCount;
			float frameCount = 0;
			while( DX.ProcessMessage() ) {
				float nowFrameCount;
				while( true ) {
					nowFrameCount = ( Environment.TickCount - baseTime ) * ( FrameRate / 1000.0f );
					if( nowFrameCount < frameCount ) {
						Thread.Sleep(1);
					}
					else {
						break;
					}
				}
				frameCount = MathF.Floor( nowFrameCount + 1.0f );

				rate.Update();

				Controller controller = Controller.Update();
				DX.ClearDrawScreen();
				screen.Draw();

				foreach( Action action in Program.actions ) {
					action();
				}
				Program.actions.Clear();
				DX.ScreenFlip();

				screen = screen.Update( controller );
				if( screen == null ) {
					break;
				}
			}
			DX.DeleteFontToHandle( Program.font );
			DX.DxLib_End();
		}

		public static void DrawString( int x , int y , string string_ , DX.COLOR_U8 color ) {
			Program.actions.Add( () => {
				DX.DrawStringToHandle( x , y , string_ , color , Program.font );
			} );
		}

		private static List< Action > actions;
		private static DX.Font font;

		/// <summary>
		/// カレントディレクトリ
		/// </summary>
		public static string CurrentDirectory {
			get {
				return Program.currentDirectory;
			}
		}

		private static string currentDirectory;

		public const int FrameRate = 60;

		public const int ScreenWidth = 512;

		public const int ScreenHeight = 384;
	}
}
