using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System;

public class DataPresistenceManager : MonoBehaviour
{
    [Header("File Storage Config")]
    [SerializeField] private string fileName;

    private GameData gameData;
    private List<IDataPresistence> dataPresistenceObjects;

    private FileDataHandler fileDataHandler;

    public static DataPresistenceManager Instance { get; private set; }

    private void Awake()
    {
        if (Instance != null)
        {
            Debug.LogError("Found more than one data presistence manager in the scene");
        }
        Instance = this;
    }

    private void Start()
    {
        fileDataHandler = new FileDataHandler(Application.persistentDataPath, fileName);
        dataPresistenceObjects = FindAllDataPresistenceObjects();
        LoadGame();
    }

    public void NewGame()
    {
        this.gameData = new GameData();
    }

    public void LoadGame()
    {
        //load any saved data from file using data handler
        this.gameData = fileDataHandler.Load();

        // Load data from a file using data presistence manager
        // if no data can be found or loaded, initialize NewGame()
        if (this.gameData == null)
        {
            Debug.Log("No data was found. Initializing using default");
            NewGame();
        }

        // push the loaded data to all scripts that need it
        foreach (IDataPresistence dataPresistenceObj in dataPresistenceObjects)
        {
            dataPresistenceObj.LoadData(gameData);
        }
    }

    public void SaveGame()
    {
        // Pass the data to other scripts so that the other can update it
        foreach (IDataPresistence dataPresistenceObj in dataPresistenceObjects)
        {
            dataPresistenceObj.SaveData(ref gameData);
        }

        // Save the data to a file using the data handler
        fileDataHandler.Save(gameData);
    }

    public void FinishQuitGame()
    {
        SaveGame();
    }

    //private void OnApplicationQuit()
    //{
    //    SaveGame();
    //}

    private List<IDataPresistence> FindAllDataPresistenceObjects()
    {
        IEnumerable<IDataPresistence> dataPresistenceObejcts = FindObjectsOfType<MonoBehaviour>().OfType<IDataPresistence>();

        return new List<IDataPresistence>(dataPresistenceObejcts);
    }
}
