using UnityEngine.UI;
using UnityEngine;
using UnityEngine.SceneManagement;

public class WorldMapManager : MonoBehaviour
{
    [Scene][SerializeField]
    private string _loadingScreenScene;
    [Scene][SerializeField]
    private string _gameScene;
    [SerializeField]
    private GameObject[] _buttonList;
    [SerializeField]
    private Sprite _unlockedIcon;
    [SerializeField]
    private Sprite _lockedIcon;
    [SerializeField]
    private Sprite _savedIcon;

    private WorldMapSave _worldMapSave;

    void Start()
    {
        //TODO: getMajorSaveFile() //Call et obtiens le chemin du fichier de sauvegarde;
        
        _worldMapSave = new WorldMapSave();
        _worldMapSave.WorldInitialition();
        UnlockLevels();

        PlayerPrefs.SetInt("LevelToLoad", -1);
    }
    
    /**
    * Debloque les niveaux deja debloquer dans le fichier de sauvegarde majeur.
    */
    public void UnlockLevels()
    {
        int counterIndex = 0;
        foreach(GameObject CurrentLevelButton in _buttonList)
        {  
            if (true || _worldMapSave.GetLevelState(counterIndex) == WorldMapSave.LevelState.UNLOCKED)
            {
                CurrentLevelButton.SetActive(true);
                ShowUnlockedIcon(CurrentLevelButton);
            }
            else if (_worldMapSave.GetLevelState(counterIndex) == WorldMapSave.LevelState.LOCKED)
            {
                //CurrentLevelButton.SetActive(false);
                ShowLockedIcon(CurrentLevelButton);
            }
            else
            {
                CurrentLevelButton.SetActive(true);
                ShowSavedIcon(CurrentLevelButton);
            }
            counterIndex++;
        }
    }

    public void WorldReinitialition()
    {
        _worldMapSave.WorldReinitialition();

    }

    private void ShowLockedIcon(GameObject currentLevelButton)
    {
        currentLevelButton.GetComponent<Image>().sprite = _lockedIcon;
    }

    private void ShowUnlockedIcon(GameObject currentLevelButton)
    {
        currentLevelButton.GetComponent<Image>().sprite = _unlockedIcon;
    }
    private void ShowSavedIcon(GameObject currentLevelButton)
    {
        currentLevelButton.GetComponent<Image>().sprite = _savedIcon;
    }

    public void CallLevelWorld1(int levelToCall)
    {
        print("Load " + levelToCall);
        if (_buttonList[levelToCall - 1].GetComponent<Image>().sprite.name != "worldmap_level_locked")
        {
            PlayerPrefs.SetString(LoadingManager.SceneToLoad, _gameScene);
            PlayerPrefs.SetInt(LoadingManager.LevelToLoad, levelToCall);
            SceneManager.LoadScene(_loadingScreenScene, LoadSceneMode.Additive);
        }
    }
}
