using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

public enum E_JsonType 
{
    JsonUtility,
    LitJson
}


public class JsonMgr : BaseMgr<JsonMgr>
{
    public T ReadData<T>(string filename, E_JsonType type = E_JsonType.LitJson, Func<T> callback = null)
    {
        string DataPath = Application.persistentDataPath + "/" + filename + ".txt";

        if (File.Exists(DataPath))
        {
            string data = File.ReadAllText(DataPath);

            T Data = default(T);

            switch (type)
            {
                case E_JsonType.JsonUtility:

                    Data = JsonUtility.FromJson<T>(data);

                    break;

                case E_JsonType.LitJson:

                    Data = JsonMapper.ToObject<T>(data);

                    break;
            }


            return Data;
        }
        else
        {
            return callback();
        }
    }

    public void SaveData(string name, object obj, E_JsonType type = E_JsonType.LitJson)
    {
        string str = "";

        switch (type)
        {
            case E_JsonType.JsonUtility:
                str = JsonUtility.ToJson(obj);
                break;
            case E_JsonType.LitJson:
                str = JsonMapper.ToJson(obj);
                break;
        }
        

        File.WriteAllBytes(Application.persistentDataPath + "/" + name + ".txt", Encoding.UTF8.GetBytes(str));
    }
}
