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

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

namespace BansheeGz.BGDatabase
{
    public abstract class BGBDSetValue<T> : BGBDCellA
    {
        public abstract SharedVariable<T> sourceVar { get; }
        protected override void Execute()
        {
            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 = sourceVar.Value;
            if (field is BGField<T>)
            {
                ((BGField<T>) field)[entity.Index] = realValue;
            }
            else
            {
                field.SetValue(entity.Index, realValue);
            }
        }
    }
}