using System;
using UnityEngine;

public class Powerup : ScriptableObject
{
    public bool isActive;
    [SerializeField]
    protected PowerupStats duration;
    [SerializeField]
    protected int[] UpgradeCosts;
    [SerializeField]
    protected int currentLevel;
    [SerializeField]
    protected int maxLevel = 3;
    public float GetDuration()
    {
        return duration.GetValue();
    }
    public void Awake()
    {
        LoadPowerupLevel();
    }
    public void OnValidate()
    {
        currentLevel = Mathf.Min(currentLevel, maxLevel);
        currentLevel = Mathf.Max(currentLevel, 1);
    }

    public bool isMaxedOut()
    {
        return currentLevel == maxLevel;
    }
    public int GetNextUpgradeCost()
    {
        if (!isMaxedOut())
        {
            return UpgradeCosts[currentLevel - 1];
        }
        else
        {
            return -1;
        }
    }
    public void Upgrade()
    {
        if (currentLevel == maxLevel) { return;}

        currentLevel++;

        SavePowerUpLevel();
    }

    private void SavePowerUpLevel()
    {
        string key = name + "Level";
        PlayerPrefs.SetInt(key, currentLevel);
    }

    private void LoadPowerupLevel()
    {
        string key = name + "Level";

        if(PlayerPrefs.HasKey(key))
        {
            currentLevel = PlayerPrefs.GetInt(key);
        }
    }

    public override string ToString()
    {
        string text = $"{name}\nLVL.{currentLevel}";

        if (isMaxedOut() )
        {
            text += "(MAX)";
        }
        return text;
    }

    public string UpgradeCostString()
    {
        if (isMaxedOut()) { return $"Upgrade\nCost:{GetNextUpgradeCost()}"; }

        return "MAXED OUT";
    }
}
