using System;
using Server;
using System.Collections;
using System.Collections.Generic;
// using Server.Gumps;
using Server.Network;
using System.IO;

namespace Server.Items
{
	public class FishingLog
	{
		public const string SAVE_PATH = @"Saves";
		public const string FILENAME = "SoutezRybaru.bin";
		
		private static Dictionary<Mobile, int> m_ScoreLog;
		private static Mobile m_LastWinner;
		
		public static Mobile LastWinner { get { return m_LastWinner; } set { m_LastWinner = value; } }

		public static void Record( int score, Mobile fisher, bool plus )
		{
			if ( m_ScoreLog == null )
				m_ScoreLog = new Dictionary<Mobile, int>();
			
			if ( m_ScoreLog.ContainsKey( fisher ) && plus )
				m_ScoreLog[ fisher ] += score;
			else
				m_ScoreLog[ fisher ] = score;
			
			if ( m_ScoreLog[ fisher ] >= 20000 )
			{
				FishingLog.Reset();
				m_LastWinner = fisher;
				World.Broadcast( 192, false, "SOUTEZ RYBARU: {0} dosahl/a skore 20 000 bodu. Zacalo nove kolo.", fisher.RawName );
				GiveReward( fisher );
			}
		}
		
		public static ArrayList GetSortedData()
		{
			if ( m_ScoreLog == null )
				return null;
			
			ArrayList SortedLog = new ArrayList();
			
			foreach (KeyValuePair<Mobile, int> db in m_ScoreLog)
			{
				SortedLog.Add( new KeyValuePair<Mobile, int>( db.Key, db.Value ) );
			}
			
			SortedLog.Sort( new ListAmountSorter() );
			
			return SortedLog;
		}
		
		private class ListAmountSorter : IComparer
		{
			public ListAmountSorter() : base()
			{
			}

			public int Compare(object a, object b)
			{
				if ( a == null || b == null || a == b || !( a is KeyValuePair<Mobile, int> ) || !( b is KeyValuePair<Mobile, int> ) )
					return 0;
				
				KeyValuePair<Mobile, int> x = ( KeyValuePair<Mobile, int> ) a;
				KeyValuePair<Mobile, int> y = ( KeyValuePair<Mobile, int> ) b;
				
				if ( x.Key == y.Key && x.Key != null && y.Key != null )
				{
					return ((Mobile)x.Key).RawName.CompareTo( ((Mobile)y.Key).RawName );
				}
				return ( ( x.Value > y.Value ) ? -1 : 1 );
			}
		}
		
		public static void Reset()
		{
			if ( m_ScoreLog != null )
				m_ScoreLog.Clear();
				
			m_LastWinner = null;
		}
		
		public static void Configure()
		{
			EventSink.WorldLoad += new WorldLoadEventHandler( OnLoad );
			EventSink.WorldSave += new WorldSaveEventHandler( OnSave );
		}
		
		private static void OnLoad()
		{
			//don't load the file if it don't exist!
			if( !File.Exists( Path.Combine( SAVE_PATH, FILENAME ) ) )
			{
				return;
			}

			using( FileStream bin = new FileStream( Path.Combine( SAVE_PATH, FILENAME ), FileMode.Open, FileAccess.Read, FileShare.Read ) )
			{
				m_ScoreLog = new Dictionary<Mobile, int>();
				
				GenericReader reader = new BinaryFileReader( new BinaryReader( bin ) );
				
				int version = reader.ReadInt();
				
				m_LastWinner = reader.ReadMobile();
				
				int count = reader.ReadInt();

				if( count > 0 )
				{
					for( int i = 0; i < count; i++ )
					{
						Mobile m = reader.ReadMobile();
						int r = reader.ReadInt();
						
						if ( m == null || r == null )
						   continue;
						else
						   m_ScoreLog.Add( m, r );
					}
				}
				
				reader.End();
			}
		}
		
		private static void OnSave( WorldSaveEventArgs e )
		{
			if( !Directory.Exists( SAVE_PATH ) )
			{
				Directory.CreateDirectory( SAVE_PATH );
			}

			GenericWriter writer = new BinaryFileWriter( Path.Combine( SAVE_PATH, FILENAME ), true );

			writer.Write( 0 );
			
			writer.Write( m_LastWinner );
			
			if ( m_ScoreLog == null )
				m_ScoreLog = new Dictionary<Mobile, int>();
			
			writer.Write( m_ScoreLog.Count );
			
			foreach( KeyValuePair<Mobile, int> kvp in m_ScoreLog )
			{
				writer.Write( kvp.Key );
				writer.Write( kvp.Value );
			}
			
			writer.Close();
		}

		public FishingLog()
		{
		}
		
/*
    		public class FishingLogGump : Gump
		{
			private ArrayList scorelist;
			
			public FishingLogGump( Mobile from ) : base(100, 60)
			{
				//290 backgroud y
				scorelist = FishingLog.GetSortedData();
				string str = "";
				
				if ( scorelist == null | scorelist.Count < 1 )
					str = "Zatim nikdo neziskal zadne body";
				else
				{
					int count = 1;
					
					foreach ( KeyValuePair<Mobile, int> kv in scorelist )
					{
						str += String.Format( "{0}. {1} - {2} bodu<br>", count, ((Mobile)kv.Key).RawName, kv.Value );
						count++;
					}
				}
				
				this.Closable=true;
				this.Disposable=true;
				this.Dragable=true;
				this.Resizable=false;
				this.AddPage(0);
				
				this.AddBackground(0, 0, 237, 338, 9200);
				this.AddHtml( 5, 25, 225, 255, str, (bool)true, (bool)true);
				this.AddLabel(64, 3, 1152, @"Soutez rybaru");
				this.AddButton(200, 310, 4005, 4007, (int)Buttons.ReloadGump, GumpButtonType.Reply, 0);
				this.AddLabel(143, 312, 0, @"Refresh");
				this.AddLabel(10, 287, 0, String.Format( "Posledni vitez: {0}", ( m_LastWinner != null ) ? m_LastWinner.RawName : "---" ));

				if ( from.AccessLevel > AccessLevel.GameMaster )
				{
					this.AddButton(10, 310, 4002, 4004, (int)Buttons.ResetStats, GumpButtonType.Reply, 0);
					this.AddLabel(45, 312, 0, @"Vymazat");
				}
			}
			
			public enum Buttons
			{
				Cancel,
				ReloadGump,
				ResetStats,
			}

			public override void OnResponse( NetState state, RelayInfo info )
			{
				Mobile from = state.Mobile;

				if ( from == null )
					return;
				
				switch( info.ButtonID )
				{
					case (int)Buttons.ReloadGump:
						{
							from.CloseGump(typeof(FishingLogGump));
							from.SendGump( new FishingLogGump( from ) );
						}
						break;
					case (int)Buttons.ResetStats:
						{
							if ( from.AccessLevel < AccessLevel.Administrator )
								return;
							
							FishingLog.Reset();
							from.CloseGump(typeof(FishingLogGump));
							from.SendGump( new FishingLogGump( from ) );
							from.SendMessage("Vysledkova listina byla vymazana");
						}
						break;
					case (int)Buttons.Cancel:
						{
						}
						break;
				}
			}
		}
*/
	
		private static void GiveReward( Mobile winner )
		{
			BaseClothing cloak = new Cloak( 1361 );
			cloak.BlessedFor = winner;
			cloak.ItemID = 0x2B05;
			cloak.Name = "<basefont color=#3366FF>Raincoat";
			cloak.Attributes.BonusHits = 30;
			cloak.Attributes.NightSight = 1;
			cloak.Attributes.Luck = 500;
			
			cloak.SkillBonuses.SetValues( 0, SkillName.Fishing, 20 );
			cloak.SkillBonuses.SetValues( 1, SkillName.Anatomy, 20 );
			cloak.SkillBonuses.SetValues( 2, SkillName.MagicResist, 20 );
			Server.Engines.XmlSpawner2.XmlAttach.AttachTo( cloak, new Server.Engines.XmlSpawner2.XmlDesc( String.Format( "Za vitezstvi v rybarske soutezi {0:D}", DateTime.Today ) ) );
			
			winner.AddToBackpack( cloak );			
			winner.AddToBackpack( new SOSPiece( 40 ) );
			winner.SendMessage( 0x482, "Odmena za vitezstvi v tomto kole souteze rybaru byla umistena do tveho batohu." );
			winner.SendMessage( 0x482, "Jako vitez nyni muzes z more vylovit i ruzne specialni predmety" );
		}
	}
}
