using UnityEngine;
using System.Collections;

public class Enemy_Dragon : BaseEnemy
{
    protected override void AIBehavior_RunTowardsPlayer()
    {
        if (playerScript == null && !GetPlayerScript())
            return;

        //tick down turn delay
        if (fTurnDelayTimer > 0.0f)
            fTurnDelayTimer -= Time.smoothDeltaTime;

        //if the player is too far, don't advance
        float fDirection = playerScript.transform.position.x - transform.position.x;

        if (Mathf.Abs(fDirection) >= 16.0f)
            return;

        bool bOldFacing = bFacingRight;

        //move towards the player
        float fDelta = bOldFacing ? 1.0f : -1.0f;

        if (fTurnDelayTimer <= 0.0f)
            fDelta = fDirection > 0 ? 1.0f : -1.0f;

        fDelta *= WalkingSpeedUnitsPerSecond * Time.smoothDeltaTime;
        if (fDelta < 0.0f)
            bFacingRight = false;
        else if (fDelta > 0.0f)
            bFacingRight = true;


        if (bOldFacing != bFacingRight)
        {
            ToggleFacing();
            fTurnDelayTimer = (TurnDelay * 0.8f) + (TurnDelay * 0.4f * Random.value);
        }

        Vector2 vImpulse = new Vector2(fDelta, 0.0f);

        if( playerScript.transform.position.y + 2 > transform.position.y )
        {
            float fYImpulse = 25.0f + 50.0f * Random.value;
            vImpulse.y = fYImpulse;
        }

        myBody.AddForce(vImpulse);
        HandleAttackRoutine();
    }


    public override void OnCollisionEnter2D(Collision2D coll)
    {
        //did we hit the player?
        if (playerScript != null && coll.gameObject == playerScript.gameObject)
        {
            fRemainingAttackTimer = 0.0f;
        }
    }

    public override void GetShotOriginAndDirection(ref Vector3 vOrigin, ref Vector2 vDirection)
    {
        vOrigin = transform.position;
        vOrigin += (Vector3)ProjectileOriginOffset;

        Vector2 vMyFacingDirection = new Vector2(bFacingRight ? 1 : -1, 0);

        Vector2 vTowardsTarget = playerScript.transform.position - transform.position;
        vTowardsTarget.Normalize();
        vDirection = vTowardsTarget;

    }

    public override void StartDying()
    {
        base.StartDying();

        SpawnPowerup();
        SpawnPowerup();
        SpawnPowerup();
        SpawnPowerup();

    }
}
