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

public class BatteryIndicatorScript : MonoBehaviour
{
    
    // The current value of the 
    [Range(0, 100)]
    public float value;

    // The current state of the battery
    public int currentState = 0;
    public int nextState = 0;


    public Sprite ChargeSprite;
    public Sprite DischargeSprite;
    public Sprite WaitingSprite;

    int tempTicks = 0;
    float chargeWait = 0;

    SpriteRenderer _spriteRenderer;

    void Start()
    {
        _spriteRenderer = this.transform.GetChild(1).GetComponent<SpriteRenderer>();
        updateState(currentState);
    }

    private void updateUI() {
        this.transform.GetChild(0).transform.localScale = new Vector3(25.8f, (1-(value / 100)) * 40f, 1f);
    }

    public void charge()
    {
        nextState = 0;
        updateState(2);
        chargeWait = 2;
    }
    public void discharge()
    {
        nextState = 1;
        updateState(2);
        chargeWait = 2;
    }

    // Check to see if this batter can currently produce charge. 
    // To produce charge it has to be on and it has to have non zero charge
    public bool hasCharge()
    {
        return currentState == 1 && value > 0;
    }

    public void updateState(int state)
    {
        currentState = state;

        switch (currentState)
        {
            case 0:
                _spriteRenderer.sprite = ChargeSprite;
                break;
            case 1:
                _spriteRenderer.sprite = DischargeSprite;
                break;
            case 2:
                _spriteRenderer.sprite = WaitingSprite;
                break;
        }
    }
    public void setValue(float value)
    {
        this.value = Mathf.Clamp(value, 0, 100);
        updateUI();
    }

    void Update()
    {
        tempTicks++;
        if (tempTicks > 10)
        {
            tempTicks = 0;

            if (currentState == 1)
            {
                setValue(value - (20f * Time.deltaTime));
            } else if (currentState == 0)
            {
                setValue(value  + (22f * Time.deltaTime));                
            }
        }
    
        // We're on cooldown to start charging
        if (chargeWait > 0)
        {
            chargeWait = Mathf.Max(0, chargeWait-Time.deltaTime);

            // If we're done with the cooldown we set the state to charge
            if (chargeWait == 0)
            {
                updateState(nextState);
                updateUI();
            }
        }
    }
}
