using UnityEngine;
using System.Collections;

public enum ETankMoveState
{
    moving =0,
    not_so_much_with_the_moving,
}

public class AIMove_Hovertank : AIMove_Base
{
    [Header("Hot Tank Action")] 
    public Vector2 MinMax_TimeInWaitState;
    public Vector2 MinMax_TimeToMoveToGoal;
    public Vector2 MinMax_NewGoalSelectRange;
    public Vector2 MinMax_RotationSpeedWhenIdle;
    public bool bOnlyMoveInFacingDirection;

    private ETankMoveState movementState;

    private float fStateTimeRemaining;

    private float fMaxTimeThisState;
    private Vector3 vStartMovePosition;
    private Vector3 vEndMovePosition;

    private float fFunRotationSpeed;

    public override bool AllowTurningToFire()
    {
        return !bOnlyMoveInFacingDirection;
    }

    void Start()
    {
        ChangeToStationary();
    }

    public override void UpdateMovement(PlayerController attackTarget)
    {
        switch (movementState)
        {
            case ETankMoveState.not_so_much_with_the_moving:
                //spin in place
                float fRot = transform.rotation.eulerAngles.z;
                fRot += fFunRotationSpeed*Time.deltaTime;
                transform.rotation = Quaternion.Euler(0, 0, fRot);

                fStateTimeRemaining -= Time.deltaTime;
                if( fStateTimeRemaining <= 0.0f )
                    ChangeToMoving();
                break;
            case ETankMoveState.moving:
                transform.position = Vector3.Lerp(vEndMovePosition, vStartMovePosition, fStateTimeRemaining / fMaxTimeThisState);
                fStateTimeRemaining -= Time.deltaTime;
                if (fStateTimeRemaining <= 0.0f)
                    ChangeToStationary();
                break;
        }
    }


    protected override void FaceObject(PlayerController faceMe)
    {
        if (bOnlyMoveInFacingDirection)
            return;

        base.FaceObject(faceMe);
    }

    void ChangeToMoving()
    {
        movementState = ETankMoveState.moving;
        vStartMovePosition = transform.position;
        vEndMovePosition = transform.position;

        Vector3 vDirection = Random.onUnitSphere;
        vDirection.z = 0;
        vDirection.Normalize();

        if (bOnlyMoveInFacingDirection)
        {
            vDirection = transform.up;
        }

        vEndMovePosition += vDirection*Random.Range(MinMax_NewGoalSelectRange.x, MinMax_NewGoalSelectRange.y);

        fMaxTimeThisState = Random.Range(MinMax_TimeToMoveToGoal.x, MinMax_TimeToMoveToGoal.y);
        fStateTimeRemaining = fMaxTimeThisState;
    }

    void ChangeToStationary()
    {
        movementState = ETankMoveState.not_so_much_with_the_moving;

        fFunRotationSpeed = Random.Range(MinMax_RotationSpeedWhenIdle.x, MinMax_RotationSpeedWhenIdle.y);

        fMaxTimeThisState = Random.Range(MinMax_TimeInWaitState.x, MinMax_TimeInWaitState.y);
        fStateTimeRemaining = fMaxTimeThisState;
    }
}
