﻿using System;
using System.Collections.Generic;
using System.IO;
using HutongGames.PlayMaker;
using UnityEngine;

namespace BansheeGz.BGDatabase
{
    [ActionCategory("BansheeGz")]
    [HutongGames.PlayMaker.Tooltip("SaveLoad addon: Save with EasySave")]
    public class BGPlaymakerLoadWithEasySave : FsmStateAction
    {
        [RequiredField] public FsmString EasySaveKey;

        public FsmString EasySavePassword;
        public FsmString FileName;

        public FsmBool SuppressExceptionLog;

        [HutongGames.PlayMaker.Tooltip("Event is fired if local EasySave save file is not found")]
        public FsmEvent FileNotFoundEvent;

        [HutongGames.PlayMaker.Tooltip("Event is fired if EasySave can not find a provided key in saved file")]
        public FsmEvent KeyNotFoundEvent;


        public override void OnEnter()
        {
            var key = EasySaveKey.Value;
            if (string.IsNullOrWhiteSpace(key)) throw new Exception("EasySaveKey is required parameter!");

            var password = EasySavePassword.Value;
            var fileName = FileName.Value;

            var noPassword = string.IsNullOrEmpty(password);
            var noFileName = string.IsNullOrEmpty(fileName);
            try
            {
                byte[] loadedData;
                if (noPassword && noFileName) loadedData = ES3.Load<byte[]>(key);
                else
                {
                    var settings = new ES3Settings();
                    if (!noPassword)
                    {
                        settings.encryptionType = ES3.EncryptionType.AES;
                        settings.encryptionPassword = password;
                    }

                    if (!noFileName) settings.path = fileName;
                    
                    loadedData = ES3.Load<byte[]>(key, settings);
                }

                BGRepo.I.Addons.Get<BGAddonSaveLoad>().Load(loadedData);
            }
            catch (KeyNotFoundException e)
            {
                if (!SuppressExceptionLog.Value) Debug.LogException(e);
                Fsm.Event(KeyNotFoundEvent);
            }
            catch (FileNotFoundException e)
            {
                if (!SuppressExceptionLog.Value) Debug.LogException(e);
                Fsm.Event(FileNotFoundEvent);
            }


            Finish();
        }
    }
}