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

[CreateAssetMenu(menuName = "KernelPanic/Player/Power", fileName = "PlayerPower.asset")]
public class PlayerPower : ScriptableObject
{
    [SerializeField]
    private bool _regenerateOnGround;
    
    [SerializeField]
    private bool _regenerateInAir;
    
    [SerializeField]
    private float _regenerateTime;

    private bool _unlocked;
    private bool _cheated;
    private bool _consumed;
    
    private float _timeSinceConsume;

    private UnityEvent _onUnlock = new UnityEvent();
    public UnityEvent OnUnlock => _onUnlock;

    public void UpdatePower( float deltaTime, bool cheat, bool grounded)
    {
        _cheated = cheat;
        
        bool regenerate = grounded ? _regenerateOnGround : _regenerateInAir;
            
        if ( _consumed && regenerate )
        {
            _timeSinceConsume += deltaTime;
            
            if ( _timeSinceConsume > _regenerateTime )
            {
                this.Reset();
            }
        }
    }

    public bool IsUnlocked => _unlocked || _cheated;
    public bool CanConsume => IsUnlocked && !_consumed;

    public void Consume()
        => _consumed = true;

    public void Reset()
    {
        _consumed = false;
        _timeSinceConsume = 0f;
    }
    
    public void Unlock()
    {
        if ( !_unlocked )
        {
            _onUnlock.Invoke();
            _unlocked = true;
        }
    }

    private void Awake()
    {
        _unlocked = false;
        _cheated = false;
    }
}
