/*
<copyright file="BGBDGetRelatedIndex.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: Get related index")]
    [TaskDescription("Get related entity index from database if any, or -1 if no value, relationSingle fields are supported")]
    public class BGBDGetRelatedIndex : 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 entity = Entity;
            var relatedEntity = ((BGFieldRelationSingle) field)[entity.Index];
            targetVar.Value = relatedEntity?.Index ?? -1;
        }
    }
}