using System;
using SimpleCore.Library;
using SimpleLite.RCS.CarTypes;
using StandardScene.Signal.Model;
using StandardScene.Signal.Plc;

namespace StandardScene.Signal.Logic
{
    /// <summary>对齐反编译 DefaultPlugin.PointControl：牵引棒升/降到位后再放行。</summary>
    public static class PointControlHandler
    {
        public static void OnStopped(Car car, SignalStopSpec spec, Func<string, PlcStationRuntime> find)
        {
            var action = spec.Part(0).Trim();
            var jgName = spec.Part(1).Trim();
            if (string.IsNullOrEmpty(action))
            {
                Diagnosis.Log($"AGV{car.id}停在地标{SignalCarAdapter.PositionId(car)}，读取配置特殊点名称为空", "SetPin", true);
                return;
            }

            var waitLeave = false;
            if (!string.IsNullOrEmpty(jgName))
            {
                var rt = find(jgName);
                if (rt != null)
                {
                    lock (rt.Sync)
                        waitLeave = rt.ReadSignal != SignalReadValue.允许离开;
                }
            }

            var pos = SignalCarAdapter.PositionId(car);
            switch (action)
            {
                case "UP1":
                    PinThenGo(car, pos, waitLeave, jgName, "SetPin1Up");
                    break;
                case "UP2":
                    PinThenGo(car, pos, waitLeave, jgName, "SetPin1Up", "SetPin2Up");
                    break;
                case "Down1":
                    PinThenGo(car, pos, waitLeave, jgName, "SetPin1Down");
                    break;
                case "Down2":
                    PinThenGo(car, pos, waitLeave, jgName, "SetPin1Down", "SetPin2Down");
                    break;
            }
        }

        private static void PinThenGo(Car car, int pos, bool waitLeave, string jgName, params string[] actions)
        {
            var done = true;
            foreach (var a in actions)
            {
                if (!SignalCarAdapter.IsActionFinish(car, a))
                    done = false;
            }

            if (!done)
            {
                foreach (var a in actions)
                    SignalCarAdapter.Control(car, a);
                return;
            }

            if (waitLeave)
            {
                Diagnosis.Log($"AGV{car.id}停在地标{pos}，需要读取{jgName}工位的允许离开", "SetPin", true);
                return;
            }

            SignalCarAdapter.Start(car);
            Diagnosis.Log($"AGV{car.id}停在地标{pos}，牵引棒动作到位，已通知AGV启动", "SetPin", true);
        }
    }
}
