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

using System;
using System.Collections.Generic;
using MaxyGames.uNode;

namespace BansheeGz.BGDatabase
{
    [NodeMenu("BansheeGz", "DB: Set related indexes")]
    public class BGUNSetRelatedIndexes : BGUNCellA, IFlowNode
    {
        public List<int> valueToSet;

        public void Execute(object graph)
        {
            var field = Field;
            if (!(field is BGFieldRelationMultiple))
                throw new Exception($"Can not set value to the database: " +
                                    $"field '{field.FullName}' is not multiple relation field!");
            var relation = (BGFieldRelationMultiple) field;
            var entity = Entity;
            if (valueToSet == null || valueToSet.Count == 0) relation[entity.Index] = null;
            else
            {
                var list = new List<BGEntity>();
                foreach (var relatedIndex in valueToSet)
                {
                    if (relatedIndex<0 || relatedIndex >= relation.RelatedMeta.CountEntities)
                        throw new Exception($"Can not write value to the database: " +
                                            $"provided related index is out of bound! Valid range is 0-{(relation.RelatedMeta.CountEntities-1)}, actual value is {relatedIndex}");
                    list.Add(relation.RelatedMeta.GetEntity(relatedIndex)); 
                }
                relation[entity.Index] = list;
            }
        }

    }
}