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

namespace Ingvar.LiveWatch.TowerDefenceDemo
{
    public class TowerBuildSlot : MonoBehaviour
    {
        public event Action OccupationChanged;
        
        public bool IsOccupied
        {
            get => _isOccupied;
            protected set
            {
                if (_isOccupied == value)
                    return;

                _isOccupied = value;
                OccupationChanged?.Invoke();
            }
        }
        public int Id { get; private set; }
        public TowerBase Tower { get; protected set; }
        public Vector3 BuildLocation => transform.position;

        [SerializeField] private GameObject _emptyStateObj;
        private WatchReference<Any> slotWatch;
        
        public void Init(int id)
        {
            Id = id;
            slotWatch = Watch.GetOrAdd<Any>("TowerSlots").GetOrAdd<Any>(Id.ToString());
            slotWatch.GetOrAdd("IsOccupied", () => IsOccupied);
        }
    
        public void Occupy(TowerBase tower)
        {
            Tower = tower;
            IsOccupied = true;
            
            _emptyStateObj.SetActive(false);
            Watch.Push(slotWatch.GetOrAdd<string>("TowerId"), tower.Id);
        }

        public void Empty()
        {
            IsOccupied = false;
            Tower = null;
            
            _emptyStateObj.SetActive(true);
            slotWatch.GetOrAdd<string>("TowerId").PushEmptyValue();
        }
        
        private bool _isOccupied;
    }
}