using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMovement : MonoBehaviour {

    enum Actions
    {
        Move,
        Attack,
    }

    [SerializeField]private float normalMoveSpeed;
    [SerializeField]private float slowMoveSpeed;
    [SerializeField]private float stoppingDistance;

    [SerializeField]private Transform trailTransform;

    [SerializeField]private float attackCooldown;
    [SerializeField]private float attackDamage;
    private float attackTimer;

    private Actions actualAction;

    private float actualMoveSpeed;
    private Vector3 monkPosition;
    private Transform myTransform;
    [SerializeField]private Animator anim; 

	// Use this for initialization
	void Awake () {
        myTransform = transform;
        monkPosition = GameObject.FindGameObjectWithTag("Monk").transform.position;        
	}

    private void OnEnable()
    {
        actualAction = Actions.Move;
        Vector3 myScale = myTransform.localScale;

        if (myTransform.position.x > monkPosition.x)
        {       
            myScale.x = -1;
            myTransform.localScale = myScale;
            trailTransform.localScale = myScale;
        }
        else 
        {            
            myScale.x = 1;
            myTransform.localScale = myScale;
            trailTransform.localScale = myScale;
        }
    }

    // Update is called once per frame
    void Update () {
        if (Globals.CanMove && !trailTransform.gameObject.activeSelf) {
            trailTransform.gameObject.SetActive(true);
        }
        else if (!Globals.CanMove && trailTransform.gameObject.activeSelf) {
            trailTransform.gameObject.SetActive(false);
        }
        switch (actualAction)
        {
            case Actions.Move:
                ChangeMoveSpeed();
                Move();
                break;

            case Actions.Attack:
                Attack();
                break;

            default:
                break;
        }        
    }

    private void ChangeMoveSpeed ()
    {
        actualMoveSpeed = Globals.CanMove ? normalMoveSpeed : slowMoveSpeed;
    }

    private void Move ()
    {
        Vector3 direction = monkPosition - myTransform.position;

        if (Mathf.Abs(direction.magnitude) >= stoppingDistance)
        {
            myTransform.position += direction.normalized * actualMoveSpeed * Time.deltaTime;
        }
        else
        {
            actualAction = Actions.Attack;
        }
    } 

    private void Attack ()
    {
        if (attackTimer >= attackCooldown)
        {
            attackTimer = 0f;
            anim.SetTrigger("Attack");
            GameObject.FindGameObjectWithTag("GameController").GetComponent<GameController>().ReduceMonkEnergy(attackDamage);
        }   
        else
        {
            attackTimer += Time.deltaTime;
        }   
             
    }
}
