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

using System;
using MaxyGames.uNode;
using UnityEngine;

namespace BansheeGz.BGDatabase
{
    public abstract class BGUNSetValue<T> : BGUNCellA, IFlowNode
    {
        public abstract T Value { get; }

        public void Execute(object graph)
        {
            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;
            if (field is BGField<T>)
            {
                ((BGField<T>) field)[entity.Index] = realValue;
            }
            else
            {
                field.SetValue(entity.Index, realValue);
            }
        }

    }
}