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

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

namespace BansheeGz.BGDatabase
{
    public abstract class BGBDGetValue<T> : BGBDCellA
    {
        public abstract SharedVariable<T> varToAssign { get; }

        protected override void Execute()
        {
            var field = Field;
            if (!(typeof(T).IsAssignableFrom(field.ValueType)))
                throw new Exception($"Can not read value from the database: " +
                                    $"field '{field.FullName}' values (type={field.ValueType.FullName}) can not be cast to {typeof(T).FullName} type!");
            var entity = Entity;
            T value;
            if (field is BGField<T>)
            {
                value = ((BGField<T>) field)[entity.Index];
            }
            else
            {
                value = (T) field.GetValue(entity.Index);
            }

            varToAssign.Value = value;
        }
    }
}