using System;
using System.Collections;
using System.Collections.Generic;
using Server;
using Server.Mobiles;

namespace Server
{
	public class BattleLust
	{
		private static Dictionary<Mobile, BattleLustTimer> m_Table = new Dictionary<Mobile, BattleLustTimer>();

		public static bool UnderBattleLust( Mobile m )
		{
			return m_Table.ContainsKey( m );
		}

		public static double GetBonus( Mobile attacker, Mobile defender )
		{
			if ( !m_Table.ContainsKey( attacker ) )
				return 1.0;

			double bonus = ( (double) ( m_Table[attacker].Bonus * Math.Max( 1, attacker.Aggressed.Count ) ) ) / 100.0;

			if ( bonus > 0.3 )
				bonus = 0.3;
// attacker.SendMessage( "BL Bonus: {0:F5}/{2}, Aggr: {1}", bonus, attacker.Aggressed.Count, m_Table[attacker].Bonus );
			return 1.0 + bonus;
		}

		public static void IncreaseBattleLust( Mobile m, int damage )
		{
			if ( m == null || damage < 30 )
				return;
			else if ( AosWeaponAttributes.GetValue( m, AosWeaponAttribute.BattleLust ) < 1 )
				return;
			else if ( m_Table.ContainsKey( m ) )
			{
				if ( m_Table[m].CanGain )
				{
					if ( m_Table[m].Bonus < 28 )
						m_Table[m].Bonus += 2;

					m_Table[m].CanGain = false;
				}
			}
			else
			{
				BattleLustTimer blt = new BattleLustTimer( m, 1 );
				blt.Start();
				m_Table.Add( m, blt );
				m.SendMessage( "The damage you received fuels your battle fury." );
			}			
// 			m.SendMessage( "Battle Lust: {0}", m_Table[m].Bonus );
		}

		public static bool DecreaseBattleLust( Mobile m )
		{
			if ( m != null && m_Table.ContainsKey( m ) )
			{
				if ( m_Table[m].Bonus > 11 )
               m_Table[m].Bonus -= 2;
            else
               m_Table[m].Bonus--;

				if ( m.Blessed || !m.Alive || m.Deleted || m_Table[m].Bonus <= 0 )
				{
					m_Table.Remove( m );
 					m.SendMessage( "Your battle fury fades." );

					return false;
				}
			}

			return true;
		}

		public class BattleLustTimer : Timer
		{
			private Mobile m_Mobile;
			public int Bonus;
			public bool CanGain;
			private int m_Count;

			public BattleLustTimer( Mobile m, int bonus ) : base( TimeSpan.FromSeconds( 2.0 ), TimeSpan.FromSeconds( 2.0 ) )
			{
				m_Mobile = m;
				Bonus = bonus;
				m_Count = 1;
            Priority = TimerPriority.OneSecond;
			}

			protected override void OnTick()
			{
				m_Count %= 3;

				if ( m_Count == 0 )
				{
					if ( m_Mobile == null || !DecreaseBattleLust( m_Mobile ) )
						Stop();
				}
				else
				{
					CanGain = true;
				}

				m_Count++;
			}
		}
	}
}