using System;
using System.Collections;
using System.Collections.Generic;
using Server;
using Server.Network;
using Server.Targeting;
using Server.Spells;
using Server.Mobiles;

namespace Server.Items
{
	public class ZoogiVejce : Item
	{
      public int Radius = 6;
		
      [Constructable]
		public ZoogiVejce() : base( 3172 )
		{
         Name = "zoogi vejce";
         Stackable = true;
         Weight = 1.0;
         Hue = 1168;
		}

		public ZoogiVejce( Serial serial ) : base( serial )
		{
		}
		
		public override void OnDoubleClick( Mobile from )
		{
			if ( !IsChildOf( from.Backpack ) )
			{
				from.SendLocalizedMessage( 1060640 ); // The item must be in your backpack to use it.
				return;
			}         
         if ( Core.AOS && (from.Paralyzed || from.Frozen || (from.Spell != null && from.Spell.IsCasting)) )
			{
				from.SendLocalizedMessage( 1075857 ); // You can not use that while paralyzed.
				return;
			}
			
			int delay = GetDelay( from );
		
			if ( delay > 0 )
			{
				from.SendLocalizedMessage( 1072529, String.Format( "{0}\t{1}", delay, delay > 1 ? "seconds." : "second." ) ); // You cannot use that for another ~1_NUM~ ~2_TIMEUNITS~
				return;
			}

			ThrowTarget targ = from.Target as ThrowTarget;

			if ( targ != null && targ.Potion == this )
				return;

			from.RevealingAction();

			if ( !m_Users.Contains( from ) )
				m_Users.Add( from );

			from.Target = new ThrowTarget( this );
		}

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

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

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

			int version = reader.ReadInt();
		}
		
		private List<Mobile> m_Users = new List<Mobile>();
		
		public void Explode_Callback( object state )
		{
			object[] states = (object[]) state;
			
			Explode( (Mobile) states[ 0 ], (Point3D) states[ 1 ], (Map) states[ 2 ] );
		}
		
		public virtual void Explode( Mobile from, Point3D loc, Map map )
		{
			if ( Deleted || map == null )
				return;

			if ( this.Amount > 1 )
			   this.Amount -= 1;
			else
            Delete();
			
			// Check if any other players are using this potion
			for ( int i = 0; i < m_Users.Count; i ++ )
			{
				ThrowTarget targ = m_Users[ i ].Target as ThrowTarget;

				if ( targ != null && targ.Potion == this )
					Target.Cancel( from );
			}
			
			// Add delay
			AddDelay( from );
			
			// Effects		
			Effects.PlaySound( loc, map, 0x207 );
			
			EffectCircle( loc, map, Radius, 0x376A );
			
			foreach ( Mobile mobile in map.GetMobilesInRange( loc, Radius ) )
			{
				if ( mobile == null || mobile.Deleted || mobile.Blessed || !mobile.Alive )
				  continue;
				  
            if ( mobile is BaseCreature && !((BaseCreature)mobile).Controlled && !mobile.IsDeadBondedPet )
				{
					((BaseCreature)mobile).Pacify( from, DateTime.Now + TimeSpan.FromSeconds( 8.0 ) ); // TODO check
				}
			}
		}
		
		#region Effects
		public static void EffectCircle( Point3D center, Map map, int radius, int effect )
		{
			Point3D current = new Point3D( center.X + radius, center.Y, center.Z );
			
			for ( int i = 0; i <= 360; i ++ )
			{							
				Point3D next = new Point3D( (int) Math.Round( Math.Cos( i ) * radius ) + center.X, (int) Math.Round( Math.Sin( i ) * radius ) + center.Y, current.Z );
				
				EffectLine( current, next, map, effect );
				
				current = next;
			}
		}
		
		public static void EffectLine( Point3D start, Point3D end, Map map, int effect )
		{			
			if( start.Equals( end ) )
				return;
		
			int difX = Math.Abs( start.X - end.X );
			int difY = Math.Abs( start.Y - end.Y );
			
			int x = start.X;
			int y = start.Y; 
			
			int avgX = (int) Math.Round( difY != 0 ? difX / (double) difY : 0 );
			int avgY = (int) Math.Round( difX != 0 ? difY / (double) difX : 0 );
			
			while ( x != end.X && y != end.Y )
			{
				Point3D p = new Point3D( x, y, start.Z );
				
				if ( map.CanFit( p, 12, true, false ) )		
					Effects.SendLocationEffect( p, map, effect, 4, 9 );
				
				if ( avgX <= 0 )
				{
					if ( x < end.X )
						x += 1;
					else if ( x > end.X )
						x -= 1;	
					avgX = (int) Math.Round( difY != 0 ? difX / (double) difY : 0 );
				}				
					
				if ( avgY <= 0 )
				{
					if ( y < end.Y )
						y += 1;
					else if ( y > end.Y )
						y -= 1;
					
					avgY = (int) Math.Round( difX != 0 ? difY / (double) difX : 0 );
				}
				
				avgX -= 1;
				avgY -= 1;
			}
		}
		#endregion
		
		#region Delay
		private static Hashtable m_Delay = new Hashtable();
		
		public static void AddDelay( Mobile m )
		{
			Timer timer = m_Delay[ m ] as Timer;
			
			if ( timer != null )
				timer.Stop();
				
			m_Delay[ m ] = Timer.DelayCall( TimeSpan.FromSeconds( 60 ), new TimerStateCallback( EndDelay_Callback ), m );	
		}
		
		public static int GetDelay( Mobile m )
		{
			Timer timer = m_Delay[ m ] as Timer;
			
			if ( timer != null && timer.Next > DateTime.Now )
				return (int) (timer.Next - DateTime.Now).TotalSeconds;
			
			return 0;
		}
		
		private static void EndDelay_Callback( object obj )
		{
			if ( obj is Mobile )
				EndDelay( (Mobile) obj );			
		}
		
		public static void EndDelay( Mobile m )
		{
			Timer timer = m_Delay[ m ] as Timer;
			
			if ( timer != null )
			{
				timer.Stop();
				m_Delay.Remove( m );
			}
		}
		#endregion		

		private class ThrowTarget : Target
		{
			private ZoogiVejce m_Potion;
			
			public ZoogiVejce Potion
			{
				get{ return m_Potion; }
			}

			public ThrowTarget( ZoogiVejce potion ) : base( 12, true, TargetFlags.None )
			{
				m_Potion = potion;
			}

			protected override void OnTarget( Mobile from, object targeted )
			{
				if ( m_Potion.Deleted || m_Potion.Map == Map.Internal )
					return;
					
				IPoint3D p = targeted as IPoint3D;

				if ( p == null || from.Map == null )
					return;

				SpellHelper.GetSurfaceTop( ref p );

				from.RevealingAction();

				IEntity to;

				if ( p is Mobile )
					to = (Mobile)p;
				else
					to = new Entity( Serial.Zero, new Point3D( p ), from.Map );

				Effects.SendMovingEffect( from, to, 3172, 7, 0, false, false, m_Potion.Hue, 0 );
				Timer.DelayCall( TimeSpan.FromMilliseconds( GetDelay( from.Location, new Point3D( p ) ) ), new TimerStateCallback( m_Potion.Explode_Callback ), new object[] { from, new Point3D( p ), from.Map } ); 				
			}
			
			public int GetDelay( Point3D start, Point3D end )
			{
				double range = Math.Sqrt( Math.Pow( start.X - end.X, 2 ) + Math.Pow( start.Y - end.Y, 2 ) );
				
				return (int) ( 1000 * range / 4 );
			}
		}
	}
}