using Otter;
using System;

namespace PenniesAreGold.objects
{
    class TroopBullet : Entity
    {
        private Entity _destiny;
        private double angleInRadians = 1;
        private int life = 150;//this number should be just slightly longer than their detection range for shooting.

        public TroopBullet(float x, float y, Entity destiny)
        {
            X = x; Y = y;
            _destiny = destiny;
            SetHitbox(2, 2, Global.Type.TROOPBULLET);
            Graphic = 
            AddGraphic(Image.CreateCircle(1, Color.Grey));
            GetDirection();
        }

        public override void Update()
        {
            base.Update();
            X -= Global.troopBulletSpeed * (float)Math.Cos(angleInRadians);
            Y -= Global.troopBulletSpeed * (float)Math.Sin(angleInRadians);
            if (life <= 0)
                Destroy();
            if (life > 0)
                life--;
            HandleCollisions();
        }

        public void HandleCollisions()//lets try this. I hope this works.
        {
            var colt = Collider.Collide((int)X, (int)Y, Global.Type.ENEMYTROOP);
            if (colt != null)
            {
                EnemyTroop t = (EnemyTroop)colt.Entity;
                t.EnemyTroopHealth--;
                if (t.EnemyTroopHealth <= 0)
                    t.Destroy();
                //play destruction sound here;
                Destroy();
            }
            var coll = Collider.Collide((int)X, (int)Y, Global.Type.ENEMYTROOPBUILDING);
            if (coll != null)
            {
                EnemyTroopBuilding t = (EnemyTroopBuilding)coll.Entity;
                t.EnemyBuildingHealth--;
                if (t.EnemyBuildingHealth <= 0)
                    t.Destroy();
                //play destruction sound here;
                Destroy();
            }
        }


        public void GetDirection()
        {
            var vector1 = new Point((int)_destiny.X, (int)_destiny.Y);
            var vector2 = new Point((int)X, (int)Y);
            angleInRadians = Math.Atan2(vector2.Y - vector1.Y, vector2.X - vector1.X);
            var angleInFrisbees = MathHelper.ToDegrees((float)angleInRadians);
            if (angleInFrisbees < 0)
            {
                angleInFrisbees += 360;
                angleInRadians = MathHelper.ToRadians(angleInFrisbees);
            }
        }

        public void Destroy()
        {
            RemoveSelf();
        }
    }
}
