using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class DataStorage : MonoBehaviour {

    [SerializeField]
    private GlobalStatisticsData globalStatistics;
    public GlobalStatisticsData GlobalStatistics { get { return this.globalStatistics; } }

    [SerializeField]
    private CurrentGameData currentGame;
    public CurrentGameData CurrentGame { get { return this.currentGame; } set { this.currentGame = value; } }


    public void PrepareData () {

        this.LoadData();
    }

    public void AssignEvents(GameEvents events) {

        events.OnAppPaused += OnAppPause;
        events.OnAppExit += OnAppQuit;

        this.globalStatistics.AssignEvents(events);
    }

    private void LoadData () {
        bool needSave = false;

        if (PlayerPrefs.HasKey(Keys.PlayerPrefs.GLOBALSTATISTICS_KEY)) {
            this.globalStatistics = JsonUtility.FromJson<GlobalStatisticsData>(PlayerPrefs.GetString(Keys.PlayerPrefs.GLOBALSTATISTICS_KEY));
        } else {
            this.globalStatistics = new GlobalStatisticsData();
            needSave = true;
        }


        if (needSave) {
            this.SaveData();
        }
    }

    private void SaveData () {

        PlayerPrefs.SetString(Keys.PlayerPrefs.GLOBALSTATISTICS_KEY, JsonUtility.ToJson(this.globalStatistics));
    }


    private void OnAppPause (bool isPaused) {
        this.SaveData();
    }

    private void OnAppQuit () {
        this.SaveData();
    }


#if UNITY_EDITOR
    [MenuItem("Tools/Clear PlayerPrefs")]
    private static void DeleteAllKeys () {
        Debug.Log("[Data Storage] Removing all saved data");
        PlayerPrefs.DeleteAll();
    }
#endif
}
