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

using System;
using Unity.VisualScripting;

namespace BansheeGz.BGDatabase
{
    [UnitCategory("BansheeGz")]
    public class BGDatabaseCreateEntity : Unit
    {
        [DoNotSerialize] public ControlInput _in;
        [DoNotSerialize] public ControlOutput _out;

        [DoNotSerialize] public ValueInput metaName;
        [DoNotSerialize] public ValueOutput entityindex;

        protected override void Definition()
        {
            _in = ControlInput("_in", Enter);
            _out = ControlOutput("_out");
            Succession(_in, _out);
            
            metaName = ValueInput<string>("Meta name", "");
            entityindex = ValueOutput<int>("Entity index");
        }

        private ControlOutput Enter(Flow flow)
        {
            var tableName = flow.GetValue<string>(metaName);
            if (string.IsNullOrEmpty(tableName)) throw new Exception("Meta name is not set!");
            var meta = BGRepo.I[tableName];
            if (meta == null) throw new Exception("Can not find meta with name " + tableName + "!");
            var newRow = meta.NewEntity();
            flow.SetValue(entityindex, newRow.Index);
            return _out;
        }
    }
}