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


class SaveMissionManager : SaveModelSystem<MissionData>
{
    public override bool SaveModelItem(MissionData model)
    {
        return base.SaveModelItem(model);
    }

    public override bool SaveModelList(List<MissionData> list)
    {
        BinaryFormatter formatter = new BinaryFormatter();

        Debug.Log("Saved Mision list at " + Path);

        if (!Directory.Exists(Path)) Directory.CreateDirectory(Path);

        /* Main logic of  conversion data format */
        var data = list; // ConvertObjectsListToListOfDataModels(list);

        FileStream stream = new FileStream(
            Path + GetFileName(ObjectListName),
            FileMode.Create
        );

        formatter.Serialize(stream, data);
        stream.Close();

        return true;
    }

    public override MissionData LoadModelItem()
    {
        return base.LoadModelItem();
    }

    public override List<MissionData> LoadModelList()
    {
        string path = Path + GetFileName(ObjectListName);

        if (File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Open);

            List<MissionData> missionsList = formatter.Deserialize(stream) as List<MissionData>;
            stream.Close();

            return missionsList; // ConvertListOfDataModelsToListOfObject(questsList);
        }
        else
        {
            Debug.Log("Save file not found in " + path);
        }

        return new List<MissionData>();
    }

    // ----------------- USELLES IN THIS CLASS -----------------
    #region unused
    // Support function

    // 1. From model to data format
    public static MissionData ConvertObjectToDataModel(Mission model)
    {
        return new MissionData(model);
    }

    public static List<MissionData> ConvertObjectsListToListOfDataModels(List<Mission> modelsList)
    {
        List<MissionData> convertedList = new List<MissionData>();

        foreach (Mission model in modelsList)
        {
            convertedList.Add(ConvertObjectToDataModel(model));
        }

        return convertedList;
    }

    // 2. From data to model format
    public static Mission ConvertDataModelToObject(MissionData dataModel)
    {
        return (Mission)dataModel.MapDataToObject();
    }

    public static List<Mission> ConvertListOfDataModelsToListOfObject(List<MissionData> dataModelsList)
    {
        List<Mission> convertedList = new List<Mission>();

        foreach (MissionData dataModel in dataModelsList)
        {
            convertedList.Add(ConvertDataModelToObject(dataModel));
        }

        return convertedList;
    }
    #endregion
}