using System;
using Server;
using Server.Mobiles;
using Server.Engines.XmlSpawner2;

namespace Server.Items
{
	public class AuberonEndGate : Moongate
	{
		private bool m_Decays;
		private DateTime m_DecayTime;
		private Timer m_Timer;

// 		public override int LabelNumber{ get{ return 1049498; } } // dark moongate

		[Constructable]
		public AuberonEndGate() : this( true )
		{
		}

		[Constructable]
		public AuberonEndGate( bool decays, Point3D loc, Map map ) : this( decays )
		{
			MoveToWorld( loc, map );
			Effects.PlaySound( loc, map, 0x20E );
		}

		[Constructable]
		public AuberonEndGate( bool decays ) : base( new Point3D( 1345, 1624, 50 ), Map.Trammel )
		{
			Dispellable = false;
			ItemID = 3948;
			Hue = 1384;
			Name = "Kralovsky hrad";

			if ( decays )
			{
				m_Decays = true;
				m_DecayTime = DateTime.Now + TimeSpan.FromMinutes( 10.0 );

				m_Timer = new InternalTimer( this, m_DecayTime );
				m_Timer.Start();
			}
		}
		
		public override void OnGateUsed( Mobile m )
		{
			if( m != null && m is PlayerMobile )
			{
				QuestJar qj = m.Backpack.FindItemByType( typeof(QuestJar) ) as QuestJar;
				
				if ( qj == null || !qj.isFull || qj.Owner != m )
				{
					m.SendMessage( 34, "Nemas u sebe plnou nadobku, odmena za zabiti draka ti nebyla pripocitana!");
					return;
				}

				HlavniQuest qatt = (HlavniQuest)XmlAttach.FindAttachment(m,typeof(HlavniQuest));
				
				if( qatt == null || !qatt.InProgress || qatt.KilledDragon )
				{
					m.SendMessage( 34, "Chyba v questu. Kontaktuj Game mastera. Odmena za zabiti draka ti nebyla pripocitana!");
					return;
				}
				
				if( qatt.InProgress && !qatt.KilledDragon )
				{
					qj.Delete();
					qatt.KilledDragon = true;
					m.SendMessage( 34, "Za zabiti darka Auberona si muzes nyni vybrat odmenu u krale!");
				}
         }		
		}

		public AuberonEndGate( Serial serial ) : base( serial )
		{
		}

		public override void OnAfterDelete()
		{
			if ( m_Timer != null )
				m_Timer.Stop();

			m_Timer = null;
         base.OnAfterDelete();
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version

			writer.Write( m_Decays );

			if ( m_Decays )
				writer.WriteDeltaTime( m_DecayTime );
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();

			switch ( version )
			{
				case 0:
				{
					m_Decays = reader.ReadBool();

					if ( m_Decays )
					{
						m_DecayTime = reader.ReadDeltaTime();

						m_Timer = new InternalTimer( this, m_DecayTime );
						m_Timer.Start();
					}

					break;
				}
			}
		}

		private class InternalTimer : Timer
		{
			private Item m_Item;

			public InternalTimer( Item item, DateTime end ) : base( end - DateTime.Now )
			{
				m_Item = item;
				Priority = TimerPriority.OneMinute;
			}

			protected override void OnTick()
			{
				m_Item.Delete();
			}
		}
	}
}