//	(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 System.IO;
using System.Xml.Serialization;

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

using UnityEngine;

namespace HutongGames.PlayMaker.Actions
{

    [ActionCategory(SaveSystemAction.ActionCategoryName)]
    [Tooltip("Saves a PlayMaker Array List Proxy component")]
    public class SaveSystemArraylistSave : SaveSystemSettingsAction
    {

        [ActionSection("Arraylist Set up")]

        [RequiredField]
        [Tooltip("The gameObject with the PlayMaker ArrayList Proxy component")]
        [CheckForComponent(typeof(PlayMakerArrayListProxy))]
        public FsmOwnerDefault gameObject;

        [Tooltip("Author defined Reference of the PlayMaker ArrayList Proxy component (necessary if several component coexists on the same GameObject)")]
        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 = "";

        PlayMakerArrayListProxy _proxy;

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

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

        public override void Enter()
        {
            this._proxy = CollectionsActions.GetArrayListProxyPointer(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 + "/Arraylist/" + this.reference;
            }

            var _list = new List<object>();

            foreach (object item in this._proxy.arrayList)
            {
                _list.Add(item);
            }

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

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

    }
}