﻿using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using HutongGames.PlayMaker.Actions;
using HutongGames.PlayMaker;
using Tooltip = HutongGames.PlayMaker.TooltipAttribute;

namespace Bayat.SaveSystem.PlayMaker
{

    public abstract class SaveSystemAction : FsmStateAction
    {

        public const string ActionCategoryName = "Bayat - Save System";

        [Tooltip("This event is triggered if an error occurs.")]
        public FsmEvent errorEvent;
        [Tooltip("If an error occurs, the error message will be stored in this variable.")]
        public FsmString errorMessage;

        public abstract void Enter();
        public abstract void OnReset();

        public override void OnEnter()
        {
            try
            {
                Enter();
            }
            catch (System.Exception e)
            {
                HandleError(e.ToString());
            }
        }

        public override void Reset()
        {
            this.errorEvent = null;
            this.errorMessage = "";
            OnReset();
        }

        public void HandleError(string msg)
        {
            this.errorMessage.Value = msg;
            if (this.errorEvent != null)
            {
                Fsm.Event(this.errorEvent);
            }
            else
            {
                LogError(msg);
            }
        }

        public void HandleTask(Task task)
        {
            if (task.IsFaulted)
            {
                HandleError(task.Exception.Message);
            }
            else if (task.IsCanceled)
            {
                HandleError("Cancelled");
            }
            else
            {
                Finish();
            }
        }

    }

}