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

public class CharacterMovement : MonoBehaviour {

    protected Character controller;
    protected NavMeshAgent navAgent;
    public NavMeshAgent NavAgent { get { return this.navAgent; } }

    [SerializeField]
    private float normalSpeed = 10;
    [SerializeField]
    private float slowSpeed = 7;
    
    [SerializeField]
    private bool isSlowedDown = false;
    public bool IsSlowerDown { get { return this.isSlowedDown; } set { this.isSlowedDown = value; } }

    private float CurrentSpeed { get { return this.isSlowedDown ? this.slowSpeed : this.normalSpeed; } }

    public virtual void PrepareMovement (Character controller) {
        this.controller = controller;
        this.navAgent = GetComponent<NavMeshAgent>();
    }

    private void Update () {
        if (this.navAgent.hasPath) {
            this.controller.CharacterAnimator.SetFloat(Keys.Animator.VELOCITY_KEY, Mathf.Clamp01(this.navAgent.velocity.magnitude));
        }
    }

    public virtual void MoveTo (Vector3 targetPosition) {
        if (this.controller.CharacterAnimator.GetBool(Keys.Animator.DIE_KEY)) {
            return;
        }

        this.controller.CharacterAnimator.SetFloat(Keys.Animator.VELOCITY_KEY, 1);
        navAgent.speed = this.CurrentSpeed;
        navAgent.SetDestination(targetPosition);
    }

    public virtual void MoveBy (Vector3 moveDirection) {
        if (this.controller.CharacterAnimator.GetBool(Keys.Animator.DIE_KEY)) {
            return;
        }

        this.controller.CharacterAnimator.SetFloat(Keys.Animator.VELOCITY_KEY, Mathf.Clamp01(moveDirection.magnitude));
        this.RotateTo(moveDirection);
        navAgent.Move(moveDirection.normalized * this.CurrentSpeed * Time.deltaTime);
    }

    public virtual void LookAt (Vector3 lookTarget) {
        if (this.controller.CharacterAnimator.GetBool(Keys.Animator.DIE_KEY)) {
            return;
        }

        lookTarget.y = navAgent.transform.position.y;
        navAgent.transform.LookAt(lookTarget);
    }

    public virtual void RotateTo (Vector3 direction) {
        if (this.controller.CharacterAnimator.GetBool(Keys.Animator.DIE_KEY)) {
            return;
        }

        if (direction.magnitude <= 0) {
            return;
        }

        direction.y = 0;
        direction = direction.normalized;
        navAgent.transform.forward = direction;
    }
}
