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

using System;
using Bolt;
using Ludiq;


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

        [DoNotSerialize] public ValueInput metaName;
        [DoNotSerialize] public ValueInput entityIndex;

        protected override void Definition()
        {
            _in = ControlInput("_in", Enter);
            _out = ControlOutput("_out");
            Succession(_in, _out);

            metaName = ValueInput<string>("Meta name", "");
            entityIndex = ValueInput<int>("Entity index", -1);
        }

        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 entityIndexValue = flow.GetValue<int>(entityIndex);
            var entity = meta.GetEntity(entityIndexValue);
            if (entity == null) throw new Exception("Can not get entity with index " + entityIndexValue + ", meta= " + tableName + "!");
            entity.Delete();
            return _out;
        }
    }
}