using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Server;
using Server.Commands;
using Server.Network;

namespace Server.Misc
{
	public class AutoRestart
	{
		public static bool Enabled = true; // is the script enabled?

		private static TimeSpan RestartZamani = TimeSpan.FromHours( 12.0 ); // time of day at which to restart
		private static TimeSpan SaveZamani = TimeSpan.FromMinutes( 1.0 ); // at what interval should the shutdown message be displayed?
		private static TimeSpan KapanmaZamani = TimeSpan.FromSeconds( 10.0 ); // how long the server should remain active before restart (period of 'server wars')

		private static bool m_Restarting = false;
		public static bool Restarting
		{
			get{ return m_Restarting; }
		}

		public static void Initialize()
		{
			CommandSystem.Register( "Restart", AccessLevel.Administrator, new CommandEventHandler( Restart_OnCommand ) );

			if ( Enabled )
				new Bekleme().Start();
		}
		public static void Restart_OnCommand( CommandEventArgs e )
		{
			if ( m_Restarting )
				e.Mobile.SendMessage( "Sunucu zaten restart atılma durumundadır." );
			else
				new Hazirlanma().Start();
		}

		private class Bekleme : Timer
		{
			public Bekleme() : base( RestartZamani, RestartZamani, 1)
			{
			}
			protected override void OnTick()
			{
				if ( !m_Restarting )
					new Hazirlanma().Start();
				Stop();
			}
		}
		private class Hazirlanma : Timer
		{
			public Hazirlanma() : base( SaveZamani, SaveZamani, 1)
			{
				Enabled = false;
				m_Restarting = true;

				BroadcastMessage( 1161, "Servera 1 dakika sonra restart atılacaktır. Restarttan sonra tekrar bağlanabilirsiniz..." );
			}
			protected override void OnTick()
			{
				AutoSave.Save();
				BroadcastMessage( 1161, "Servera restart atılıyor... Restarttan sonra tekrar bağlanabilirsiniz..." );
				new Kapanma().Start();
				Stop();
			}
		}
		private class Kapanma : Timer
		{
			public Kapanma() : base( KapanmaZamani, KapanmaZamani, 1)
			{
			}
			protected override void OnTick()
			{
				Process.Start( Core.ExePath );
				Core.Process.Kill();
				Stop();
			}
		}
		public static void BroadcastMessage( int hue, string message ) 
		{ 
			foreach ( NetState state in NetState.Instances )
				if ( state.Mobile != null )
					state.Mobile.SendMessage( hue, message );
		}
	}
}