/*
<copyright file="BGGCGetRelatedList.cs" company="BansheeGz">
    Copyright (c) 2018-2021 All Rights Reserved
</copyright>
*/

using System.Collections.Generic;
using GameCreator.Core;
using GameCreator.Variables;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;

#endif

namespace BansheeGz.BGDatabase
{
    /// <summary>
    ///  get indexes of related entities 
    /// </summary>
    public class BGGCGetRelatedList : BGGCGetA
    {
        public HelperListVariable listVariables = new HelperListVariable();
        public override VariableProperty TargetVariable
        {
            get { return null; }
        }

        public override bool IsSupported(BGField field)
        {
            return field is BGFieldRelationMultiple || field is BGFieldNested;
        }

        public override bool InstantExecute(GameObject target, IAction[] actions, int index)
        {
            if (listVariables == null)
            {
                Debug.Log("WARNING! BGDatabase: can not access listVariables variable!");
                return true;
            }

            var listVar = listVariables.GetListVariables(target);
            if (listVar == null)
            {
                Debug.Log("WARNING! BGDatabase: listVar is null!");
                return true;
            }
            if (listVar.type != Variable.DataType.Number)
            {
                Debug.Log("WARNING! BGDatabase: can not use list variable, cause list var type is not number!");
                return true;
            }
            
            var cell = GetCell(target);
            if (cell == null)
            {
                Debug.Log("WARNING! BGDatabase: can not access a target cell!");
                return true;
            }

            var valueValue = (List<BGEntity>) cell.Value.Value;
            VariablesManager.ListClear(listVar);

            if (valueValue != null)
            {
                foreach (var val in valueValue) VariablesManager.ListPush(listVar, ListVariables.Position.Last, val.Index);
            }

            return true;
        }

        // +--------------------------------------------------------------------------------------+
        // | EDITOR                                                                               |
        // +--------------------------------------------------------------------------------------+
#if UNITY_EDITOR
        public static new string NAME = "BansheeGz/Get related list";
        protected override string Title => "BGDatabase: Get related list";

        public override void EditorGui()
        {
            base.EditorGui();
            EditorGUILayout.PropertyField(Prop(nameof(listVariables)));
        }
#endif
    }
}