using UnityEngine;
using ScrambleKit.FX;

public class HumanAI : MonoBehaviour 
{
    public FXTrigger CommandAcceptedFX;

    public float SpeedFactor = 0.9f;
    public float GoalArrivalThreshold = 0.3f;

    private bool hasGoal;
    private Vector2 goalPos;

    private MoveController move;

    void Start()
    {
        move = GetComponent<MoveController>();
    }

    public void AssignGoal(Vector2 position)
    {
        hasGoal = true;
        goalPos = position;
        Invoke("FX", Random.Range(0.05f, .3f));
    }

    public void ClearGoal()
    {
        hasGoal = false;
    }

    private void FX()
    {
        CommandAcceptedFX.Trigger(transform);
    }

    void Update()
    {
        if (HumanControl.ActiveHuman == transform)
        {
            hasGoal = false;
            return;
        }

        if (!hasGoal)
        {
            move.MoveDir = Vector2.zero;
            return;
        }

        if (ArrivedAtGoal())
            hasGoal = false;
        else
            MoveTowardGoal();
    }

    private bool ArrivedAtGoal()
    {
        return (goalPos - (Vector2)transform.position).magnitude <= GoalArrivalThreshold;
    }

    private void MoveTowardGoal()
    {
        Vector2 delta = (goalPos - (Vector2)transform.position);
        move.MoveDir = delta.normalized * SpeedFactor;
    }
}
