using System;
using System.IO;
using Server;
using Server.Commands;

namespace Server.Misc
{
	public class AutoSave : Timer
	{
		private static TimeSpan m_Delay = TimeSpan.FromMinutes( 30.0 );
		private static TimeSpan m_Warning = TimeSpan.FromSeconds( 15.0 );

		public static void Initialize()
		{
			new AutoSave().Start();
			CommandSystem.Register( "SetSaves", AccessLevel.Administrator, new CommandEventHandler( SetSaves_OnCommand ) );
		}

		private static bool m_SavesEnabled = true;

		public static bool SavesEnabled
		{
			get{ return m_SavesEnabled; }
			set{ m_SavesEnabled = value; }
		}

		[Usage( "SetSaves <true | false>" )]
		[Description( "Enables or disables automatic shard saving." )]
		public static void SetSaves_OnCommand( CommandEventArgs e )
		{
			if ( e.Length == 1 )
			{
				m_SavesEnabled = e.GetBoolean( 0 );
				e.Mobile.SendMessage( "Saves have been {0}.", m_SavesEnabled ? "enabled" : "disabled" );
			}
			else
			{
				e.Mobile.SendMessage( "Format: SetSaves <true | false>" );
			}
		}

		public AutoSave() : base( m_Delay - m_Warning, m_Delay )
		{
			Priority = TimerPriority.OneMinute;
		}

		protected override void OnTick()
		{
			if ( !m_SavesEnabled || AutoRestart.Restarting )
				return;

			if ( m_Warning == TimeSpan.Zero )
			{
				Save();
			}
			else
			{
				int s = (int)m_Warning.TotalSeconds;
				int m = s / 60;
				s %= 60;

				if ( m > 0 && s > 0 )
					World.Broadcast( 0x35, true, "Server {0} dakika ve {1} saniye sonra save alacaktir...", m, s );
				else if ( m > 0 )
					World.Broadcast( 0x35, true, "Server {0} dakika sonra save alacaktir...", m );
				else
					World.Broadcast( 0x35, true, "Server {0} saniye sonra save alacaktir.", s );

				Timer.DelayCall( m_Warning, new TimerCallback( Save ) );
			}
		}

		public static void Save()
		{
			World.Broadcast( 0x35, true, "Oyun kaydediliyor. Lutfen bekleyin..." );

			try{ Backup(); }
			catch (Exception e) { Console.WriteLine("WARNING: Automatic backup FAILED: {0}", e); }

			DateTime Basla = DateTime.Now;
			World.Save( false );

			DateTime Bitir = DateTime.Now;
			World.Broadcast( 0x35, true, "Kaydetme {0:F1} saniyede tamamlandi.", (Bitir - Basla).TotalSeconds );

		}

		private static void Backup()
		{
			DateTime now = DateTime.Now;

			String text = String.Format("Yedek{0}{1}", now.ToString("MM"), now.ToString("dd"));
			string saves = Path.Combine( Core.BaseDirectory, "Saves" );
			if ( !Directory.Exists( saves ) )
				return;

			string root = Path.Combine( Core.BaseDirectory, "Yedekler" );
			if ( !Directory.Exists( root ) )
				Directory.CreateDirectory( root );

			if ( !Directory.Exists( Path.Combine( root, text ) ) )
			{
				try{ Directory.Move( saves, FormatDirectory( root, text ) ); }
				catch{}
			}
			else
			{
				string[] existing = Directory.GetDirectories( root );
				DirectoryInfo dir = Match( existing, "YedekSon" );
				if ( dir != null )
					dir.Delete( true );
				Directory.Move( saves, FormatDirectory( root, "YedekSon" ) );
			}
		}

		private static DirectoryInfo Match( string[] paths, string match )
		{
			for ( int i = 0; i < paths.Length; ++i )
			{
				DirectoryInfo info = new DirectoryInfo( paths[i] );

				if ( info.Name.StartsWith( match ) )
					return info;
			}

			return null;
		}

		private static string FormatDirectory( string root, string name )
		{
			return Path.Combine( root, String.Format( "{0}", name ) );
		}
	}
}