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

using System;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

namespace BansheeGz.BGDatabase
{
    [TaskCategory("BansheeGz")]
    [TaskName("BGDatabase: Set related index")]
    [TaskDescription("Set related entity by using related entity index, pass -1 to remove the value, relationSingle fields are supported")]
    public class BGBDSetRelatedIndex : BGBDCellA
    {
        [RequiredField] public SharedInt targetVar;

        protected override void Execute()
        {
            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 = targetVar.Value;
            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);
            }
        }
    }
}