//	(c) Jean Fabre, 2011-2018 All rights reserved.
//	http://www.fabrejean.net

// INSTRUCTIONS
// Drop a PlayMakerArrayList script onto a GameObject, and define a unique name for reference if several PlayMakerArrayList coexists on that GameObject.
// In this Action interface, link that GameObject in "arrayListObject" and input the reference name if defined. 
// Note: You can directly reference that GameObject or store it in an Fsm variable or global Fsm variable

using System.Collections;
using System.Collections.Generic;

using Bayat.SaveSystem;
using Bayat.SaveSystem.PlayMaker;

using UnityEngine;

namespace HutongGames.PlayMaker.Actions
{
    [ActionCategory(SaveSystemAction.ActionCategoryName)]
    [Tooltip("Saves a PlayMaker HashTable Proxy component")]
    public class SaveSystemHashtableSave : SaveSystemSettingsAction
    {

        [ActionSection("Hashtable Set up")]

        [RequiredField]
        [Tooltip("The Game Object to add the Hashtable Component to.")]
        public FsmOwnerDefault gameObject;

        [Tooltip("Author defined Reference of the PlayMaker arrayList proxy component ( necessary if several component coexists on the same GameObject")]
        [UIHint(UIHint.FsmString)]
        public FsmString reference;

        [ActionSection("Save System Set Up")]

        [Tooltip("A unique key for this save. For example, the object's name if no other objects use the same name.")]
        public FsmString key = "";


        PlayMakerHashTableProxy _proxy;


        public override void OnReset()
        {
            this.gameObject = null;
            this.reference = null;

            this.key = new FsmString() { UseVariable = true };
        }

        public override void Enter()
        {
            this._proxy = CollectionsActions.GetHashTableProxyPointer(Fsm.GetOwnerDefaultTarget(this.gameObject), this.reference.Value, false);
            if (this._proxy != null)
            {
                Execute();
            }

        }

        public void Execute()
        {

            string _key = this.key.Value;
            if (string.IsNullOrEmpty(_key))
            {
                _key = Fsm.GameObjectName + "/" + Fsm.Name + "/Hashtable/" + this.reference;
            }

            Dictionary<string, object> _dict = new Dictionary<string, object>();


            foreach (object key in this._proxy.hashTable.Keys)
            {
                _dict[(string)key] = this._proxy.hashTable[key];
            }

            if (this.settingsPreset)
            {
                SaveSystemAPI.SaveAsync(_key, _dict, this.settingsPreset.CustomSettings).ContinueWith(HandleTask);
            }
            else
            {

                SaveSystemAPI.SaveAsync(_key, _dict).ContinueWith(HandleTask);
            }
        }

    }
}