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

using System;
using NodeCanvas.Framework;
using ParadoxNotion.Design;

namespace BansheeGz.BGDatabase
{
    [Category("BansheeGz")]
    [Name("BGDatabase: Set value")]
    [Description("Set cell value using value variable as a source")]
    public class BGNCSetValue<T> : BGNCCellA
    {
        [RequiredField]
        public BBParameter<T> value;

        protected override void OnExecute()
        {
            var field = Field;
            if (field.ReadOnly)
                throw new Exception($"Can not write value to the database: " +
                                    $"field '{field.FullName}' is read-only field!");

            if (!(typeof(T).IsAssignableFrom(field.ValueType)))
                throw new Exception($"Can not write value to the database: " +
                                    $"field '{field.FullName}' values (type={field.ValueType.FullName}) can not be cast to {typeof(T).FullName} type!");

            var entity = Entity;
            var realValue = value.value;
            if (field is BGField<T>)
            {
                ((BGField<T>) field)[entity.Index] = realValue;
            }
            else
            {
                field.SetValue(entity.Index, realValue);
            }
            EndAction(true);
        }
    }
}