using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Animation;
using AR;
using COMM;

namespace vmsnet
{
    public partial class FMain
    {
        Boolean bRunConnection = true;
        Task thConnection;   //연결체크

        void bwDeviceConnection()
        {
            //TimeSpan ts;
            while (this.IsDisposed == false && bRunConnection)
            {
                if (VAR.I32.Get(EVarI32.DevConnectSeq) == 0)
                {
                    //하나의 대상만 연결시도를 하지 않게하기 위해 연결횟수를 가지고 로테이션한다.
                    if (PUB.DAQ.Any() == false)
                    {
                        PUB.log.AddE($"Connect Error : No DAQ List");
                        System.Threading.Thread.Sleep(5000);
                    }
                    else
                    {
                        var DAQ = PUB.DAQ.Where(t => t.isOn == false).OrderBy(t => t.ConnTryCount).FirstOrDefault();
                        if (DAQ != null)
                        {
                            //비활성화되어있다면 비활성 처리한다.
                            if (DAQ.Disable == false)
                            {
                                PUB.RaiseRemoteCommandEvent(rCommand.DisableUIItems, DAQ.idx);
                                DAQ.Disable = true;
                            }

                            //장치의연결시도
                            try
                            {
                                var ts = DateTime.Now - DAQ.ConnectTry;
                                if (ts.TotalSeconds > 5)
                                {
                                    //discnt += 1
                                    PUB.StatusMSG($"{DAQ.Name} 연결시도중({DAQ.IP}:{DAQ.PORT})");
                                    //PUB.log.Add(AR.Log.ETYPE.NORMAL, "DA100 연결시도");
                                    DAQ.ConnectTry = DateTime.Now;
                                    if (DAQ.ConnTryCount > 65530)
                                        DAQ.ConnTryCount = 0;
                                    else
                                        DAQ.ConnTryCount += 1;

                                    PUB.RaiseRemoteCommandEvent(rCommand.DAQTryConnect, DAQ.idx);
                                    if (DAQ.Connect().Result)
                                    {
                                        PUB.log.Add(AR.Log.ETYPE.NORMAL, $"{DAQ.Name} 연결성공({DAQ.IP}:{DAQ.PORT})");
                                        PUB.RaiseRemoteCommandEvent(rCommand.DAQConnected, DAQ.idx);
                                    }
                                    else
                                    {
                                        PUB.log.Add(AR.Log.ETYPE.NORMAL, $"{DAQ.Name} 연결실패({DAQ.IP}:{DAQ.PORT})");
                                        PUB.RaiseRemoteCommandEvent(rCommand.DAQDisconnected, DAQ.idx);
                                    }

                                    PUB.log.AddAT($"[{DAQ.idx}]Connect to {DAQ.IP}:{DAQ.PORT}");
                                }
                            }
                            catch (Exception ex)
                            {
                                PUB.log.AddE($"[{DAQ.idx}] Connect error {DAQ.IP}:{DAQ.PORT} Message={ex.Message}");
                            }
                        }
                        else System.Threading.Thread.Sleep(1000);
                    }

                    VAR.I32[EVarI32.DevConnectSeq] += 1;
                }
                else if (VAR.I32.Get(EVarI32.DevConnectSeq) == 1)
                {
                    //Master K
                    if (PUB.masterk.IsInit == false && PUB.CONFIG.plc_port.StartsWith("COM"))
                    {
                        var ts = VAR.TIME.RUN(EVarTime.CONNTRY_PLC);
                        if (ts.TotalSeconds > 5)
                        {
                            PUB.masterk.Init(PUB.CONFIG.plc_port);
                            VAR.TIME[EVarTime.CONNTRY_PLC] = DateTime.Now;
                            VAR.I32[EVarI32.CONNTRY_PLC] += 1;
                            PUB.log.Add($"MasterK Connect to {PUB.CONFIG.plc_port}");
                        }
                        else System.Threading.Thread.Sleep(500);
                    }
                    else
                    {
                        if (VAR.I32[EVarI32.CONNTRY_PLC] == 0)
                        {
                            //PUB.log.AddAT($"Master K Port Not set : {PUB.CONFIG.plc_port}");
                            VAR.I32[EVarI32.CONNTRY_PLC] += 1;
                        }
                        System.Threading.Thread.Sleep(1000);
                    }
                    VAR.I32[EVarI32.DevConnectSeq] += 1;
                }
                else //indicator
                {
                    if (PUB.indicator.IsOpen == false && PUB.CONFIG.indicator_port.StartsWith("COM"))
                    {
                        var ts = VAR.TIME.RUN(EVarTime.CONNTRY_INDICATOR);
                        if (ts.TotalSeconds > 5)
                        {
                            PUB.indicator.SlaveID = (byte)PUB.CONFIG.indicator_slaveno;
                            PUB.indicator.Configure.BaudRate = PUB.CONFIG.indicator_baud;
                            PUB.indicator.Open(PUB.CONFIG.indicator_port);
                            VAR.TIME[EVarTime.CONNTRY_INDICATOR] = DateTime.Now;
                            VAR.I32[EVarI32.CONNTRY_INDICATOR] += 1;
                            PUB.log.Add($"Indicator Connect to {PUB.CONFIG.indicator_port}");
                        }
                        else System.Threading.Thread.Sleep(500);
                    }
                    else
                    {
                        if (VAR.I32[EVarI32.CONNTRY_INDICATOR] == 0)
                        {
                            //PUB.log.AddAT($"Indicator Port Not set : {PUB.CONFIG.indicator_port}");
                            VAR.I32[EVarI32.CONNTRY_INDICATOR] += 1;
                        }
                        System.Threading.Thread.Sleep(1000);
                    }
                    VAR.I32.Clear(EVarI32.DevConnectSeq);
                }
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}
