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

using System;
using Unity.VisualScripting;

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

        [DoNotSerialize] public ValueInput metaName;
        [DoNotSerialize] public ValueInput entityIndex1;
        [DoNotSerialize] public ValueInput entityIndex2;

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

            metaName = ValueInput<string>("Meta name", "");
            entityIndex1 = ValueInput<int>("Entity Index1", -1);
            entityIndex2 = ValueInput<int>("Entity Index2", -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 index1 = flow.GetValue<int>(entityIndex1);
            var index2 = flow.GetValue<int>(entityIndex2);
            meta.SwapEntities(index1, index2);
            return _out;
        }
    }
}