using System;
using SimpleCore.Library;
using StandardScene.Signal.Model;

namespace StandardScene.Signal.Plc
{
    /// <summary>机构运行态。写信号赋值会清 WriteSuccess，驱动 Worker 重写 PLC。</summary>
    public sealed class PlcStationRuntime
    {
        private SignalWriteValue _writeSignal;
        private SignalReadValue _readSignal;
        private SignalWriteValue _readWriteSignal;

        public PlcStationRuntime(PlcStationModel config)
        {
            Config = config ?? throw new ArgumentNullException(nameof(config));
        }

        public PlcStationModel Config { get; }

        /// <summary>扫车线程与 PLC Worker 共用运行态，写入时加此锁。</summary>
        public object Sync { get; } = new object();

        public SignalReadValue ReadSignal
        {
            get => _readSignal;
            set
            {
                if (_readSignal != value)
                    Diagnosis.Log($"{Config.JgName} 读信号 {_readSignal} → {value}", "PLC", true);
                _readSignal = value;
            }
        }

        public SignalWriteValue WriteSignal
        {
            get => _writeSignal;
            set
            {
                if (_writeSignal != value)
                    Diagnosis.Log($"{Config.JgName} 写信号 {_writeSignal} → {value}", "PLC", true);
                _writeSignal = value;
                WriteSuccess = false;
            }
        }

        public SignalWriteValue ReadWriteSignal
        {
            get => _readWriteSignal;
            set
            {
                if (_readWriteSignal != value)
                    Diagnosis.Log($"{Config.JgName} 回读写值 {_readWriteSignal} → {value}", "PLC", true);
                _readWriteSignal = value;
            }
        }

        public int InAgvNo { get; set; }
        public int RequestInAgvNo { get; set; }
        public bool IsConnected { get; set; }
        public bool WriteSuccess { get; set; }
        public bool Heart { get; set; }
        public string LastError { get; set; } = "";

        public PlcStationSnapshot ToSnapshot() => new PlcStationSnapshot
        {
            JgName = Config.JgName,
            IsConnected = IsConnected,
            ReadSignal = ReadSignal.ToString(),
            WriteSignal = WriteSignal.ToString(),
            ReadWriteSignal = ReadWriteSignal.ToString(),
            InAgvNo = InAgvNo,
            RequestInAgvNo = RequestInAgvNo,
            WriteSuccess = WriteSuccess,
            Heart = Heart,
            LastError = LastError ?? ""
        };
    }
}
