using System;
using System.Collections.Generic;
using System.Linq;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.AI;
using VOID.Generic.Navigation;
using VOID.Generic.Objects.Door.Events;
using VOID.Generic.Objects.Door.State;

namespace VOID.Generic.Objects.Door
{
    [Serializable]
    public class DoorObjectState : ObjectComponent<DoorObject>
    {
        #region Initialize

        protected override void SelfInitialize()
        {
            _doorObstacles = parent.GetComponents<NavMeshObstacle>().ToList();
            
            parent.GetComponentInChildren<DoorOpenerTrigger>().door = parent;
        }

        protected override void EventInitialize()
        {
            parent.doorEvents.onOpen.AddListener(OnOpen);
            parent.doorEvents.onClose.AddListener(OnClose);
            parent.doorEvents.onLock.AddListener(OnLock);
            parent.doorEvents.onUnlock.AddListener(OnUnlock);
        }

        protected override void Initialize()
        {
            if (isOpen)
            {
                parent.Unlock();
                parent.Open();
                return;
            }

            if (isLocked)
            {
                parent.Close();
                parent.Lock();
                return;
            }

            parent.Close();
            parent.Unlock();
        }

        #endregion

        private List<NavMeshObstacle> _doorObstacles;

        [DisableInPlayMode] public bool isOpen;
        [DisableInPlayMode] public bool isLocked;

        private void OnOpen(DoorEvent doorEvent)
        {
            isOpen = true;
            parent.doorAnimator.PlayOpen();
        }
        
        private void OnClose(DoorEvent doorEvent)
        {
            isOpen = false;
            parent.doorAnimator.PlayClose();
        }

        private void OnLock(DoorEvent doorEvent)
        {
            isLocked = true;
            _doorObstacles.ForEach(obstacle => obstacle.enabled = true);
            NavigationManager.current.UpdateNavMesh(new Bounds(parent.transform.position, Vector3.one * parent.basicData.radius));
        }
        
        private void OnUnlock(DoorEvent doorEvent)
        {
            isLocked = false;
            _doorObstacles.ForEach(obstacle => obstacle.enabled = false);
            NavigationManager.current.UpdateNavMesh(new Bounds(parent.transform.position, Vector3.one * parent.basicData.radius));
        }
    }
}
