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

using System;
using MaxyGames.uNode;

namespace BansheeGz.BGDatabase
{
    [NodeMenu("BansheeGz", "DB: Set related index")]
    public class BGUNSetRelatedIndex : BGUNCellA, IFlowNode
    {
        public int valueToSet;

        public void Execute(object graph)
        {
            var field = Field;
            if (!(field is BGFieldRelationSingle))
                throw new Exception($"Can not read value from the database: " +
                                    $"field '{field.FullName}' is not single relation field!");
            var relation = (BGFieldRelationSingle) field;
            var entity = Entity;
            var relatedIndex = valueToSet;
            if (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}");
            if (relatedIndex < 0) relation[entity.Index] = null;
            else
            {
                relation[entity.Index] = relation.RelatedMeta.GetEntity(relatedIndex);
            }
        }

    }
}