using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public static class LoadSavePlayerStats {

    // The three slots of data saved.
    public static PlayerStats[] savedGames = new PlayerStats[3];
    
    // Temporal data for scene changing.
    public static PlayerStats tmp;

    // Auxiliar boolean to knowing where the Player comes from a load statt.
    public static bool isLoaded = false;

    // Load data filename and extension.
    private static string filename = "/savedGames";
    private static string extension = ".gd";
    
    // Load the three slots from the binary files
    public static void Load() {

        for (int i = 0; i < LoadSavePlayerStats.savedGames.Length; i++) {

            if (File.Exists(Application.persistentDataPath + filename + i + ".gd")) {
                Debug.Log("Loading data from " + Application.persistentDataPath + filename + i + ".gd...");
                BinaryFormatter bf = new BinaryFormatter();
                FileStream file = File.Open(Application.persistentDataPath + filename + i + extension, FileMode.Open);
                LoadSavePlayerStats.savedGames[i] = (PlayerStats)bf.Deserialize(file);
                file.Close();
            } else {
                LoadSavePlayerStats.savedGames[i] = null;
            }        
        }

        //for (int i = 0; i < LoadSavePlayerStats.savedGames.Length; i++)
        //{
        //    Debug.Log("SLOT " + i);
        //    if (LoadSavePlayerStats.savedGames[i] != null) Debug.Log(LoadSavePlayerStats.savedGames[i].ToString());
        //    else Debug.Log("Empty");
        //}

    }

    // Load a concrete position.
    public static PlayerStats Load(int pos) {
        return LoadSavePlayerStats.savedGames[pos]; 
    }

    // Save a stats in a concrete position.
    public static void Save(PlayerStats current, int pos) {
        LoadSavePlayerStats.savedGames[pos] = (current);
        
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + filename + + pos + extension);
        bf.Serialize(file, LoadSavePlayerStats.savedGames[pos]);
        file.Close();
    }


    // Delete all the data, also from local memory.
    public static void RemoveData(){
        for (int i = 0; i < LoadSavePlayerStats.savedGames.Length; i++) {
            LoadSavePlayerStats.savedGames[i] = null;
            File.Delete(Application.persistentDataPath + filename + i + extension);
        }

        File.Delete(Application.persistentDataPath + "/savedGames.gd");        
    }
    
    // Temporal saveswap.
    public static void saveTMP(PlayerStats current)    {
        LoadSavePlayerStats.tmp = (current);
        LoadSavePlayerStats.isLoaded = false;
    }
}
