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

using System;
using System.Collections.Generic;
using NodeCanvas.Framework;
using ParadoxNotion.Design;

namespace BansheeGz.BGDatabase
{
    [Category("BansheeGz")]
    [Name("BGDatabase: Set related indexes")]
    [Description("Set related entities by using a list their indexes, relationMultiple fields are supported")]
    public class BGNCSetRelatedIndexes : BGNCCellA
    {
        [RequiredField] public BBParameter<List<int>> targetVar;

        protected override void OnExecute()
        {
            var field = Field;
            var isMultiple = field is BGFieldRelationMultiple;
            if (!(field is BGFieldRelationMultiple))
                throw new Exception($"Can not write value to the database: " +
                                    $"field '{field.FullName}' has wrong type: only relationMultiple fields are supported!");
            var entity = Entity;
            var relation = (BGFieldRelationMultiple) field;
            var value = targetVar.value;
            if (value == null || value.Count == 0) relation[entity.Index] = null;
            else
            {
                var relatedList = new List<BGEntity>(value.Count);
                var count = relation.RelatedMeta.CountEntities;
                foreach (var index in value)
                {
                    if (index < 0 || index >= count)
                        throw new Exception($"Can not write value to the database: " +
                                            $"one of the provided related indexes is out of bound! Valid range is 0-{(count - 1)}, actual value is {index}");
                    relatedList.Add(relation.RelatedMeta.GetEntity(index));
                }
                relation[entity.Index] = relatedList;
            }

            targetVar.value = value;
            EndAction(true);
        }
    }
}