using System.IO;
using System.Runtime.InteropServices;
using HutongGames.PlayMaker;
using UnityEngine;

namespace BansheeGz.BGDatabase
{
    [ActionCategory("BansheeGz")]
    public class BGSaveGameWebGl : FsmStateAction
    {
        protected const string FileExt = "sav";

        [RequiredField] public FsmString gameName;
        [RequiredField] public FsmString fileName;
        public FsmBool debug;

        protected string FolderPath
        {
            get { return "/idbfs/" + gameName; }
        }

        protected string FilePath
        {
            get { return FolderPath + "/" + fileName + '.' + FileExt; }
        }

        public override void Reset()
        {
            gameName = null;
            fileName = null;
            debug = null;
        }

        public override void OnEnter()
        {
            var folder = FolderPath;
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
            var fullFileName = FilePath;
            if(debug.Value) Debug.Log("BGSaveGameWebGl: Trying to save to : " + fullFileName);
            if (!File.Exists(fullFileName))
            {
                using (File.Create(fullFileName)) { }
            }
            File.WriteAllBytes(fullFileName, BGRepo.I.Addons.Get<BGAddonSaveLoad>().Save());
            WebIdbfsSync();
            if(debug.Value) Debug.Log("BGSaveGameWebGl: Saved ok to " + fullFileName);
            Finish();
        }

        [DllImport("__Internal")]
        public static extern string WebIdbfsSync();
    }
}