using System.Collections.Generic;
using Schema;
using Sirenix.OdinInspector;
using UnityEngine;
using VOID.Generic.AI.Schema;
using VOID.Generic.Objects.Abstract.Events;
using VOID.Generic.Objects.Unit;

namespace VOID.Generic.AI
{
    [DisallowMultipleComponent]
    public class UnitAI : MonoBehaviour
    {
        private UnitObject _unit;
        private UnitObjectSchemaAgent _schemaAgent;

        [Title("AI Schemas")]
        [DisableOnPlay, SerializeField, Required] private Graph _passiveSchema;
        [DisableOnPlay, SerializeField, Required] private Graph _combatSchema;

        [Title("Variables for schemas")]
        public List<Transform> patrol;
        
        public void Awake()
        {
            enabled = false;
            
            if (!_passiveSchema || !_combatSchema)
            {
                Debug.LogError("Both AI schemas are REQUIRED!");
                return;
            }

            _unit = GetComponent<UnitObject>();
            if (!_unit)
            {
                Debug.LogError("Found no UnitObject!");
                return;
            }

            enabled = true;
            
            // Disable AI when unit is dead or enable when revived
            _unit.basicEvents.onDeathAfter.AddListener(OnDeathAfter);
            _unit.basicEvents.onRevive.AddListener(OnRevive);

            // Change AI schemas between passive and combat
            _unit.basicEvents.onTurnQueueEnter.AddListener(OnTurnQueueEnter);
            _unit.basicEvents.onTurnQueueLeave.AddListener(OnTurnQueueLeave);
            
            _schemaAgent = gameObject.AddComponent<UnitObjectSchemaAgent>();
            _schemaAgent.hideFlags = HideFlags.NotEditable;
            _schemaAgent.unit = _unit;
            _schemaAgent.unitAI = this;
            _schemaAgent.ChangeSchema(_passiveSchema);
        }

        private void OnTurnQueueEnter(TurnEvent turnEvent)
        {
            _schemaAgent.ChangeSchema(_combatSchema);
        }

        private void OnTurnQueueLeave(TurnEvent turnEvent)
        {
            _schemaAgent.ChangeSchema(_passiveSchema);
        }

        private void OnDeathAfter(DeathEvent deathEvent) {
            _schemaAgent.enabled = false;
        }

        private void OnRevive(ReviveEvent reviveEvent) {
            _schemaAgent.enabled = true;
        }
    }
}