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

public class MinionBar : MonoBehaviour {

    public GameObject minionIconPrefab;

    List<Entity> minionTypes;
    List<MinionIcon> minionIcons;
    int currentIndex;

    void Awake() {
        minionTypes = new List<Entity>();
        minionIcons = new List<MinionIcon>();
    }

    void Start() {
        UpdateReload(0f);
    }

    public void ChangeSelectedIcon(InputAction.CallbackContext context) {

        float floatDelta = context.ReadValue<float>();
        int delta = 0;
        if (floatDelta > 0.5f) {
            delta = 1;
        } else if (floatDelta < -0.5f) {
            delta = -1;
        }

        minionIcons[currentIndex].UnSelect();

        currentIndex += delta;
        if (currentIndex >= minionIcons.Count) {
            currentIndex = 0;
        } else if (currentIndex < 0) {
            currentIndex = minionIcons.Count - 1;
        }

        minionIcons[currentIndex].Select();
        // print("new selected minion type : " + currentIndex.ToString());
    }

    public void AddMinionType(Entity newMinionPrefab) {
        minionTypes.Add(newMinionPrefab);
        MinionIcon newIcon = Instantiate(minionIconPrefab, transform).GetComponent<MinionIcon>();
        minionIcons.Add(newIcon);
        // minionIcons[i].icon = minionTypes.icon; // TODO
        newIcon.indexInMinionList = minionIcons.Count;
        if (currentIndex == minionIcons.Count - 1) {
            newIcon.Select();
        } else {
            newIcon.UnSelect();
        }
    }

    public void UpdateReload(float reloadFraction) {
        float reloadFractionCorrected = reloadFraction;
        if (reloadFractionCorrected < 0f) {
            reloadFractionCorrected = 0f;
        } else if (reloadFractionCorrected > 1f) {
            reloadFractionCorrected = 1f;
        }

        foreach (MinionIcon icon in minionIcons) {
            icon.reloadSlider.value = reloadFractionCorrected;
        }
    }

    public Entity GetCurrentMinion() {
        return minionTypes[currentIndex];
    }

}
