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

public class Orc : Monster {

    const float ATTACK_RANGE = 1.5f;

    public float strikeTime = 1f;

    public float strikeActiveTime = 0.8f;

    public float moveSpeed = 1.8f;

    public float turnSpeed = 90;

    public GameObject swordHit;

    bool attacking;

    float attackTime;

    Animator anim;

    void Awake()
    {
        anim = GetComponentInChildren<Animator>();
    }

    // Update is called once per frame
    void Update () {
        if (!GlobalUpdate())
            return;

        if (!attacking)
            transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(playerReference.transform.position - transform.position, Vector3.up), turnSpeed * Time.deltaTime);
        else
        {
            float prevAttack = attackTime;
            attackTime = Mathf.Max(0, attackTime - Time.deltaTime);
            //anim.SetBool("attacking", false);

            if (attackTime == 0)
            {
                attacking = false;
                swordHit.SetActive(false);
                
            }
            else if (attackTime <= strikeActiveTime && prevAttack > strikeActiveTime)
            {
                swordHit.SetActive(true);
            }
        }
	}

    void FixedUpdate()
    {
        if (!GlobalFixedUpdate())
            return;

        anim.SetBool("walking", false);

        if (!attacking)
        {
            Vector3 distance = playerReference.transform.position - transform.position;
            if (distance.sqrMagnitude > ATTACK_RANGE * ATTACK_RANGE)
            {
                character.SimpleMove(distance.normalized * moveSpeed);
                anim.SetBool("walking", true);
            }
            else if (Mathf.Abs(Vector3.Angle(transform.forward, distance)) <= 30f)
            {
                attacking = true;
                attackTime = strikeTime;

                anim.SetTrigger("attacking");
            }
        }
    }
}
