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

[RequireComponent(typeof(WaypointSystem) )]
public class AgentMove : MonoBehaviour
{
    [SerializeField] private float m_speed = 5.0f;
    private WaypointSystem m_waypointSystem;
    private Vision m_vision;
    private Transform m_target;
    private bool m_canMove = true;

    private void Start()
    {
        m_waypointSystem = transform.GetComponent<WaypointSystem>();
        m_vision = transform.GetComponent<Vision>();
        m_target = m_waypointSystem.GetWayPointTransform();
        m_waypointSystem.onCanMove += OnCanMoveResponse;
        m_waypointSystem.onStopMove += OnStopMoveResponse;
        m_vision.onFoundPlayer += OnFoundPlayerResponse;
    }
    
    private void OnDisable()
    {
        m_waypointSystem.onCanMove -= OnCanMoveResponse;
        m_waypointSystem.onStopMove -= OnStopMoveResponse;
        m_vision.onFoundPlayer -= OnFoundPlayerResponse;
    }
    
    private void OnDestroy()
    {
        m_waypointSystem.onCanMove -= OnCanMoveResponse;
        m_waypointSystem.onStopMove -= OnStopMoveResponse;
        m_vision.onFoundPlayer -= OnFoundPlayerResponse;
    }

    void OnCanMoveResponse()
    {
        SetTarget();
        SetMove(true);
    }
    public void SetTarget()
    {
        m_target = m_waypointSystem.GetWayPointTransform();
    }

    void OnStopMoveResponse()
    {
        SetMove(false);
    }

    void OnFoundPlayerResponse()
    {
        SetMove(false);
    }

    public void SetMove(bool _move)
    {
        m_canMove = _move;
    }

    private void FixedUpdate()
    {
        if (m_target && m_canMove)
        {
            transform.position = transform.position + transform.forward * Time.deltaTime * m_speed;
        }
    }
}
