using GameDev.CoreSystems;
using ScriptableObjectArchitecture;
using UnityEngine;

namespace AsteroidGame.Handlers
{
    public class PowerHandler : HandlerBase
    {
        [Header("State")]
        [SerializeField] private IntReference _powerConsumption;
        [SerializeField] private int _powerConsumptionPeak;
        [SerializeField] private IntReference _powerCapacity;
        [SerializeField] private float _powerFactor;
        [SerializeField] private bool _powerLost;

        [Header("Connections")]
        [SerializeField] private SoPowerSystemRuntimeSet _activePowerStructures;

        private void Update()
        {
            _powerConsumption.Value = 0;
            _powerConsumptionPeak = 0;
            _powerCapacity.Value = 0;
            foreach (var structure in _activePowerStructures)
            {
                if (structure.IsConsumer)
                {
                    _powerConsumption.Value += structure.GetCurrentPower();
                    _powerConsumptionPeak += structure.GetMaxPower();
                }

                if (structure.IsGenerator)
                {
                    _powerCapacity.Value += structure.GetMaxPower();
                }
            }

            _powerLost = _powerConsumption.Value > _powerCapacity.Value;

            foreach (IPowerSystem structure in _activePowerStructures)
            {
                if (structure.IsConsumer)
                {
                    structure.PowerLost = _powerLost;
                }
            }

            _powerFactor = _powerCapacity.Value > 0 ? (float)_powerConsumption.Value / _powerCapacity.Value : 0;
        }

        public int GetMaxPower() => _powerCapacity.Value;

        public int GetCurrentPower() => _powerConsumption.Value;

        public float GetPowerFactor() => _powerFactor;
    }
}