using System;
using Server.Targeting;
using Server.Spells.Fourth;

namespace Server.Spells.Spellweaving
{
	public class WildfireSpell : ArcanistSpell
	{
		private static SpellInfo m_Info = new SpellInfo(
                "Wildfire", "Haelyn",
                SpellCircle.Eighth, // 0.5 + 2.0 = 2.5s base cast delay
				-1,
				false
			);

        public override double RequiredSkill { get { return 66.0; } }
        public override int RequiredMana { get { return 50; } }

        public WildfireSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info )
		{
		}

		public override void OnCast()
		{
			Caster.Target = new InternalTarget( this );
		}

		public void Target( Point3D p )
		{
			if( !Caster.CanSee( p ) )
			{
				Caster.SendLocalizedMessage( 500237 ); // Target can not be seen.
			}
			else if( CheckSequence() )
			{
				Effects.PlaySound( p, Caster.Map, 0x5CF );

				int level = GetFocusLevel();
				double skill = Caster.Skills[SkillName.Spellweaving].Value;

				int tiles = 2 + level; // 2 + FocusLevel
				int damage = 20 + level; // 15 + FocusLevel
				int duration = (int)Math.Floor( skill / 10 ) + level; // Floor( Skill / 24 ) + FocusLevel
								
				/*
				 *		x	x	x
				 * 
				 *		x	o	x
				 * 
				 *		x	x	x
				 */
				for( int x = -tiles; x <= tiles; x += tiles )
				{
					for( int y = -tiles; y <= tiles; y += tiles )
					{
						SpawnField( p, x, y, Caster.Map, damage, duration );
					}
				}
			}

			FinishSequence();
		}

		public void SpawnField( Point3D p, int x, int y, Map map, int damage, int duration )
		{
			if( x == 0 && y == 0 )
				return;

			p.X += x;
			p.Y += y;

			IPoint3D o = p as IPoint3D;

			SpellHelper.GetSurfaceTop( ref o );

			p = new Point3D( o );

			int itemID = Utility.RandomBool() ? 0x398C : 0x3996;

			//if( map.CanSpawnMobile( p ) )
			new FireFieldSpell.InternalItem( itemID, p, Caster, map, TimeSpan.FromSeconds( duration ), Utility.RandomMinMax( -2, 2 ), damage );
		}

		public class InternalTarget : Target
		{
			private WildfireSpell m_Owner;

			public InternalTarget( WildfireSpell owner ) : base( 12, true, TargetFlags.None )
			{
				m_Owner = owner;
			}

			protected override void OnTarget( Mobile m, object o )
			{
				if( o is IPoint3D )
				{
					m_Owner.Target( new Point3D( (IPoint3D)o ) );
				}
			}

			protected override void OnTargetFinish( Mobile m )
			{
				m_Owner.FinishSequence();
			}
		}
	}
}