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

[RequireComponent(typeof(Rigidbody),typeof(WaypointSystem) )]
public class Lookat : MonoBehaviour
{
    [Range(0.0f, 1.0f)] [SerializeField] private float m_rotateSpeed = 0.1f;
    private WaypointSystem m_waypointSystem;
    private GameObject m_target;
    private Quaternion m_lookRotation = Quaternion.identity;
    private Rigidbody m_rigidbody;
    private Vision m_vision;
    private BlackBoard m_blackboard;
    
    private void Start()
    {
        m_waypointSystem = transform.GetComponent<WaypointSystem>();
        m_rigidbody = GetComponent<Rigidbody>();
        m_vision = transform.GetComponent<Vision>();
        m_blackboard = (BlackBoard)FindObjectOfType(typeof(BlackBoard));
        m_target = new GameObject();
        m_target.name = this.name + " target";
        m_target.transform.position = m_waypointSystem.GetWayPointTransform().position;
        m_waypointSystem.onCanMove += OnCanMoveResponse;
        m_vision.onFoundPlayer += OnFoundPlayerResponse;
    }

    private void OnDisable()
    {
        m_waypointSystem.onCanMove -= OnCanMoveResponse;
        m_vision.onFoundPlayer -= OnFoundPlayerResponse;
    }
    
    private void OnDestroy()
    {
        m_waypointSystem.onCanMove -= OnCanMoveResponse;
        m_vision.onFoundPlayer -= OnFoundPlayerResponse;
    }

    void OnFoundPlayerResponse()
    {
        Vector3 pos = new Vector3(m_blackboard.playerPos.x, transform.position.y, m_blackboard.playerPos.z);
        m_target.transform.position = pos;
    }
    
    void OnCanMoveResponse()
    {
        SetTarget();
    }
    
    public void SetTarget()
    {
        m_target.transform.position = m_waypointSystem.GetWayPointTransform().position;
    }

    private void Update()
    {
        if (m_target)
        {
            var lookRotation = Quaternion.LookRotation(m_target.transform.position - transform.position);
            m_lookRotation = Quaternion.Lerp(m_lookRotation, lookRotation, m_rotateSpeed);
        }
    }

    private void FixedUpdate()
    {
        if(m_target)
            m_rigidbody.MoveRotation(m_lookRotation);
    }
}
