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

using System;
using System.Collections.Generic;
using GameCreator.Runtime.Common;
using GameCreator.Runtime.Variables;
using UnityEngine;

namespace BansheeGz.BGDatabase
{
    [Title("BGDatabase: set related list")]
    [Category("BansheeGz/set related list")]
    [Serializable]
    public class BGGCSetRelatedList : BGGCSetA
    {
        [SerializeField] private CollectorListVariable value = new CollectorListVariable();

        public override string Title => "BGDatabase: set related list";
        public override bool IsSupported(BGField field) => field is BGFieldRelationMultiple;

        protected override void Set(Args args, BGGCCell cell)
        {
            List<int> list = null;
            var listVar = value.Get(Args.EMPTY);
            if (listVar.Count > 0)
            {
                list = new List<int>(listVar.Count);
                foreach (var item in listVar) list.Add((int)item);
            }

            var relatedMeta = ((BGFieldRelationMultiple)cell.field).RelatedMeta;

            List<BGEntity> val = null;
            if (list != null && list.Count > 0)
            {
                val = new List<BGEntity>();
                foreach (var v in list)
                {
                    if (v < 0 || v >= relatedMeta.CountEntities)
                    {
                        Debug.Log("WARNING! BGDatabase: can not assign multiple relation value! One of the values is in invalid range! valid range=[0,"
                                  + (relatedMeta.CountEntities - 1) + "], invalid value=" + v);
                        return;
                    }

                    val.Add(relatedMeta.GetEntity(v));
                }
            }

            cell.Value = val;
        }
    }
}