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

// Handles scene-persistent player data
public class PlayerManager : MonoBehaviour
{
    public int CurrentToolIndex;
    private SerializableDictionary<ToolEnum, bool> unlockedToolDict = null;

    public bool IsToolUnlocked(ToolEnum tool)
    {
        if (unlockedToolDict.TryGetValue(tool, out bool unlocked)) return unlocked;

        // If no tool dict saved, init the default one (only None is unlocked)
        unlockedToolDict = new SerializableDictionary<ToolEnum, bool>();

        foreach (ToolEnum toolType in Enum.GetValues(typeof(ToolEnum)))
        {
            if (toolType == ToolEnum.None)
                unlockedToolDict.Add(toolType, true);
            else
                unlockedToolDict.Add(toolType, false);
        }

        // Try again
        if (unlockedToolDict.TryGetValue(tool, out bool unlockedRetry)) return unlockedRetry;
        return false;
    }

    #region Player Data Save/Load
    public void SavePlayerData(ref PlayerSaveData data)
    {
        data.activeToolIndex = GameManager.Instance.PlayerManager.CurrentToolIndex;
        data.dougPosition = GameManager.Instance.PlayerController.transform.position;
        data.currentScene = SceneManager.GetActiveScene().name;
        data.unlockedToolDict = unlockedToolDict;
    }

    public void LoadPlayerData(PlayerSaveData data)
    {
        if (data.currentScene != null && data.currentScene != SceneManager.GetActiveScene().name)
        {
            GameManager.Instance.GoToMapPoint(new MapPoint(data.currentScene, data.dougPosition), true);
        }
        else
        {
            GameManager.Instance.PlayerManager.CurrentToolIndex = data.activeToolIndex;
            GameManager.Instance.PlayerController.transform.position = data.dougPosition;
        }

        if (data.unlockedToolDict != null)
        {
            unlockedToolDict = data.unlockedToolDict;
        }
        else
        {
            // If no tool dict saved, init the default one (only None is unlocked)
            unlockedToolDict = new SerializableDictionary<ToolEnum, bool>();

            foreach (ToolEnum toolType in Enum.GetValues(typeof(ToolEnum)))
            {
                if (toolType == ToolEnum.None)
                    unlockedToolDict.Add(toolType, true);
                else
                    unlockedToolDict.Add(toolType, false);   
            }
        }
    }
    #endregion
}

[System.Serializable]
public struct PlayerSaveData
{
    public int activeToolIndex;
    public Vector3 dougPosition;
    public string currentScene;
    public SerializableDictionary<ToolEnum, bool> unlockedToolDict;
}
