using System.Collections.Generic;
using System;
using System.Drawing;
using System.Diagnostics;
using System.Data;
using System.Collections;
using System.Windows.Forms;
using System.Xml.Linq;
using AR;
using System.Windows.Media;
using System.Media;
using System.IO;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Threading.Tasks;
using vmsnet;

namespace vmsnet
{

    sealed class PUB
    {
        public static List<string> KA1_IndexList = new List<string>();
        public static List<string> KA2_IndexList = new List<string>();
        public static float KA1_SUM= 0f;
        public static float KA2_SUM = 0f;

        public static AR.Log log;
        public static HMI.CGROUP printgrp = null;
        public static bool RaiseSound1 = false;
        public static bool RaiseSound2 = false;
        public static bool RaiseSound = false;
        public static string ExtCommand = "";
        public static bool setupmode = false;
        public static bool NotExitMonitor = false;
        public static CFDB DB;
        public static CFDBA Alarm;
        public static CFDBK KADB;
        public static CMachine[] DAQ;
        static string lastDAQerrMsg = "";
        static DateTime lastDAQerrTime = DateTime.Now;
        public static CSetting CONFIG;
        public static CDesignSetting DESIGN;
        public static CTrendSetting TREND;

        public static arDev.MasterK masterk;
        public static DigitalIndicator indicator;
        public static int sleepoffset = 0; ////쓰레드슬립시간

        /// <summary>
        /// 측정값(전압)이 들어있다(mcidx/unitno/chidx)
        /// </summary>
        public static int[,,] Values;
        /// <summary>
        /// 측정값(시간)이 들어있다(mcidx/unitno/chidx)
        /// yyyy-MM-dd HH:mm:ss
        /// </summary>
        public static string[,,] Times;
        /// <summary>
        /// 채널번호가 들어있다(1부터시작~)
        /// </summary>
        public static int[,,] ChNos;

        /// <summary>
        /// 소수점 위치(채널정보에 포함되어있음)
        /// </summary>
        public static byte[,,] ChDecPos;

        /// <summary>
        /// 채널의 옵셋값(최종값에 더해짐)
        /// </summary>
        public static float[,,] ChVOffset;

        public static bool[,,] ChfirstSave;

        /// <summary>
        /// 채널사용여부
        /// </summary>
        public static bool[,,] chUse;

        public static string lasttime = "";
        public static event EventHandler<RemoteCommand> RemoteCommandEvent;
        public static Frm_Sub subWindow;
        public static FMain mainWindow;
        public static DocumentElement DS = new DocumentElement();
        public static bool runerror = false; ////실행오류


        public static string lastStatueMessage = "";

        public static HMI.CGROUP[] MainGroup = null;
        public static HMI.CGROUP[] SubGroup = null;

        public static System.Text.StringBuilder StartErrmsg = new System.Text.StringBuilder();
        public static int WindowCount = 0;

        private static Frm_SMsg fSMsg = null;
        private static Frm_Msg fMsg = null;
        private static MediaPlayer mplayer = null;

        public static AR.Device.CStateMachine sm = null;
        public static DateTime StartupTime = DateTime.Now;

        /// <summary>
        /// 입력한 채널의 파일버퍼기준의 인덱스값을 반환합니다.
        /// 각 파일은 최대 160개의 채널데이터를 가지고 있다.
        /// 161번 채널의 경우 2번째 파일의 001번 데이터이다
        /// 160번 채널의 경우 1번째 파일의 160번 데이터이다
        /// </summary>
        /// <param name="ValueIdx">채널번호(1~)</param>
        /// <returns></returns>
        public static int GetChannelIndexFromFileBuffer(int ValueIdx)
        {
            //각 파일당 160개씩 저장되어있으므로 채널번호를 통해서 파일의 위치를 파악해야한다.
            int quotient = ValueIdx / 160; // 몫
            int remainder = ValueIdx % 160; // 나머지

            //나머지가 0인경우에는 마지막데이터이다
            //그외의 경우에는 나머지가 해당 인덱스가 된다.
            return remainder == 0 ? quotient * 160 : remainder;

        }
      
        public static void RaiseRemoteCommandEvent(rCommand cmd, object data = null)
        {
            RemoteCommandEvent?.Invoke(null, new RemoteCommand(cmd, data));
        }

        public static void smsg(string m)
        {
            if (fSMsg == null || fSMsg.IsDisposed)
                fSMsg = new Frm_SMsg();

            if (fSMsg.Visible == false) fSMsg.Show();

            fSMsg.Activate();
            fSMsg.Label1.Text = m;
            Application.DoEvents();
            if (m == "") fSMsg.Close();
        }

        public static Font GetFontFromStr(string strfontbuffer)
        {
            try
            {
                string[] fontstr = strfontbuffer.Split(",".ToCharArray());
                FontStyle fstyle = (FontStyle)(int.Parse(fontstr[2]));
                return new Font(fontstr[0], float.Parse(fontstr[1]), fstyle);
            }
            catch
            {
                return new Font("Tahoma", 10, FontStyle.Bold);
            }
        }

        public static void workmsg(string m)
        {
            if (fMsg == null || fMsg.IsDisposed)
                fMsg = new Frm_Msg();

            if (fMsg.Visible == false) fMsg.Show();

            fMsg.Activate();
            fMsg.lb_Status.Text = m;
            Application.DoEvents();
            if (m == "") fMsg.Close();
        }

        ////타임정보를 숫자로 반환함
        public static decimal get_TimeNumber(DateTime time)
        {
            return time.Hour * 3600 + time.Minute * 60 + time.Second;
        }
        public static void ShowForm(Form f, Type ftype, params object[] data)
        {
            if (f == null || f.IsDisposed)
                f = (Form)Activator.CreateInstance(ftype, data);

            f.Show();

            if (f.WindowState == FormWindowState.Minimized)
                f.WindowState = FormWindowState.Normal;
            else if (f.Visible == false)
                f.Visible = true;

            f.Activate();
        }

        public static string get_TimeString(decimal timenumber, string fn)
        {
            ////파일명에 년/월/일이 있음
            string[] fnb = fn.Split("\\".ToCharArray());
            string Filename = fnb[fnb.Length - 1];
            string daystr = fnb[fnb.Length - 2];
            string monstr = fnb[fnb.Length - 3];
            string yearstr = fnb[fnb.Length - 4];

            ////timenumber를 다시 시,분,초 로 변환한다.
            decimal namugy = timenumber;
            int hour = (int)(Math.Floor(namugy / 3600));
            namugy = namugy - (hour * 3600);
            int min = (int)(Math.Floor(namugy / 60));
            namugy = namugy - (min * 60);
            int sec = (int)namugy;

            return yearstr + "-" + monstr + "-" + daystr + " " + hour.ToString("00") + ":" + min.ToString("00") + ":" + sec.ToString("00");
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="mcidx">0부터 시작~</param>
        /// <param name="unit">0부터 시작~</param>
        /// <param name="ch">1부터 시작</param>
        /// <param name="value"></param>
        /// <param name="time">yyyy-MM-dd HH:mm:ss</param>
        /// <returns></returns>
        public static bool AddMeasureValue(int mcidx, int unit, int ch, int value, string time)
        {
            var l0 = PUB.Values.GetUpperBound(0) + 1;   //mc array size
            var l1 = PUB.Values.GetUpperBound(1) + 1;   //unit array size
            var l2 = PUB.Values.GetUpperBound(2) + 1;   //ch array size

            if (mcidx < l0 && unit < l1 && ch > 0 && ch <= l2)
            {
                try
                {
                    PUB.Values[mcidx, unit, ch - 1] = value;
                    PUB.Times[mcidx, unit, ch - 1] = time;
                    return true;
                }
                catch (Exception)
                {
                    if (System.Diagnostics.Debugger.IsAttached)
                        Console.WriteLine($"수신데이터입력실패 M/C:{mcidx},Unit:{unit},CH:{ch - 1}");
                    return false;
                }
            }
            else
            {
                if (System.Diagnostics.Debugger.IsAttached)
                    Console.WriteLine($"수신데이터배열크기오류 mc:{mcidx},unit:{unit},ch:{ch}");
                return false;
            }
        }


        /// <summary>
        /// 채널인덱스를 가지고 버퍼인덱스를 계산 합니다.
        /// 1개의 버퍼는 최대 160개를 저장 합니다.
        /// </summary>
        /// <param name="chno">1부터시작하는 채널값</param>
        /// <returns></returns>
        public static int ConvertChIndexToBufferIndex(int chno)
        {
            var ValueIdx = chno;
            int quotient = ValueIdx / 160; // 몫
            int remainder = ValueIdx % 160; // 나머지
            if (remainder == 0) ValueIdx = quotient - 1;
            else ValueIdx = quotient;
            if (ValueIdx < 0) ValueIdx = 0;
            return ValueIdx;
        }

        /// <summary>
        /// 지정 장비에서 데이터를 수신한 후 Pub.Value, Time 변수에 값을 기록합니다.
        /// 데이터 수집오류가 발생한다면 False 를 반환 합니다.
        /// </summary>
        /// <param name="m"></param>
        /// <param name="startCH"></param>
        /// <param name="endCH"></param>
        /// <returns></returns>
        public static List<NotifyData> GetMeasureData(CMachine m, int startCH, int endCH)
        {
            List<NotifyData> returnvalue = new List<NotifyData>();
            try
            {
                string LastTime = "";
                var retval = m.GetDataBinary(startCH, endCH);
                if (retval != null)
                {
                    foreach (CMachine.ReturnData R in retval)
                    {
                        if (R.ch < 1 && R.unit < 1) continue;
                        LastTime = R.time;
                        if (R.err == false)
                        {
                            var addok = AddMeasureValue(m.idx, R.unit, R.ch, R.value, R.time);
                            if (addok)
                            {
                                returnvalue.Add(new NotifyData
                                {
                                    idx_m = m.idx,
                                    idx_u = R.unit,
                                    idx_c = R.ch - 1,
                                    value = R.value,
                                    time = R.time,
                                    chno = PUB.ChNos[m.idx, R.unit, R.ch - 1],
                                    offset = PUB.ChVOffset[m.idx, R.unit, R.ch - 1],
                                    decpos = PUB.ChDecPos[m.idx, R.unit, R.ch - 1],
                                    use = PUB.chUse[m.idx, R.unit, R.ch - 1],

                                });
                            }

                        }
                    }
                    if (LastTime.CompareTo(PUB.lasttime) > 0) PUB.lasttime = LastTime;
                    return returnvalue;
                }
                else return returnvalue;

            }
            catch (Exception ex)
            {
                if (m.DoRequest)
                {
                    PUB.log.AddE($"Reset Data Request Mode(Ing -> ready)");
                    m.DoRequest = false;
                }

                var ermsg = $"Data Request ({startCH}~{endCH}) Error " + ex.Message.ToString();
                var addlog = false;
                if (ermsg.Equals(lastDAQerrMsg) == false) addlog = true;
                else
                {
                    var tserdaq = DateTime.Now - lastDAQerrTime;
                    if (tserdaq.TotalSeconds > 30) addlog = true;
                }
                if (addlog)
                {
                    PUB.log.Add(AR.Log.ETYPE.ERROR, ermsg);
                    lastDAQerrMsg = ermsg;
                    lastDAQerrTime = DateTime.Now;
                }
                return returnvalue;
            }
        }



        public static void ProcessDisplayControl(HMI.DispCtrl DispCtrl1, rCommand Command, object Data)
        {
            switch (Command)
            {
                case rCommand.DAQTryConnect:
                    break;
                case rCommand.ValueUpdate:
                    if (DispCtrl1.GROUPS.Any() && DispCtrl1.GROUPS.First().Items.First().활성화 == false)
                    {
                        foreach (HMI.CGROUP g in DispCtrl1.GROUPS)
                        {
                            g.Items.Where(t => t.사용).ToList().ForEach(t => t.활성화 = true);
                        }
                    }
                    DispCtrl1.Invalidate();
                    break;
                case rCommand.DisableUIItems:
                    var midx = int.Parse(Data.ToString());
                    foreach (HMI.CGROUP g in DispCtrl1.GROUPS)
                    {
                        g.Items.Where(t => t.idx_dev == midx).ToList().ForEach(t => t.활성화 = false);
                    }
                    break;
                case rCommand.EnableUIItems:
                    var midx2 = int.Parse(Data.ToString());
                    foreach (HMI.CGROUP g in DispCtrl1.GROUPS)
                    {
                        g.Items.Where(t => t.idx_dev == midx2 && t.사용).ToList().ForEach(t => t.활성화 = true);
                    }
                    break;
                case rCommand.UpdateAlarmSetting:
                    var midx3 = int.Parse(Data.ToString());

                    //알람정보를 가져온다
                    var Drow = PUB.DS.GRP.Where(t => t.IDX == midx3).FirstOrDefault();
                    if (Drow != null)
                    {
                        foreach (HMI.CGROUP t in DispCtrl1.GROUPS.Where(t => t.IDX == midx3))
                        {
                            t.AlarmType = Drow.ALAMTYPE;
                            t.HIGH = Drow.ALAMH;
                            t.LOW = Drow.ALAML;
                            t.UP = Drow.AUTOH;
                            t.nbh = Drow.NBH;
                            t.nbl = Drow.NBL;
                            t._alamcount = 0;
                            t._alamcountlb = 0;
                        }
                    }
                    break;
                default:
                    PUB.log.AddAT($"처리되지않은 RCOMMAND:{Command},DATA:{Data}");
                    break;
            }
        }


        /// <summary>
        /// 대상 테이블의 파일을 기록합니다.
        /// 기본값으로는 아래 테이블이 지정됩니다
        /// "DEVICE", "GRP", "NORMAL", "WIN", "VIEWGROUP", "CHANNEL"
        /// </summary>
        /// <param name="tablenames"></param>
        public static void SaveConfigFile(params string[] tablenames )
        {
            ////설정정보를 가져온다.
            string[] BackTables = tablenames;
            if(tablenames == null || tablenames.Any()==false)
                BackTables = new string[] { "DEVICE", "GRP", "NORMAL", "WIN", "VIEWGROUP", "CHANNEL" };
       
            foreach (string tabname in BackTables)
            {
                PUB.DS.Tables[tabname].AcceptChanges();
                System.IO.FileInfo fn = new System.IO.FileInfo(PUB.CONFIG.GetDatabasePath() + "\\Database\\Config\\" + tabname + ".xml");
                if (fn.Directory.Exists == false)
                {
                    fn.Directory.Create();
                }
                PUB.DS.Tables[tabname].WriteXml(fn.FullName, XmlWriteMode.IgnoreSchema);
            }
        }



        /// <summary>
        /// 시간정보를 숫자로반환합니다.(년도는 2자리로 표기됨)
        /// </summary>
        /// <param name="time">날짜시간형태의 값이어야함 </param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static decimal Get_timenumber(string time, bool noyearmon = false)
        {
            DateTime dd = DateTime.Parse(time);
            int year = (int.Parse(dd.ToString("yy"))) * 12 * 31 * 86400;
            int mon = dd.Month * 31 * 86400;
            int day = dd.Day * 86400;
            int hh = dd.Hour * 3600;
            int mm = dd.Minute * 60;
            if (noyearmon)
            {
                return day + hh + mm + dd.Second;
            }
            else
            {
                return year + mon + day + hh + mm + dd.Second;
            }
        }

        /// <summary>
        /// 숫자값의 날짜를 문자로 변경해준다.
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string Get_TimeStrFromNumber(decimal time)
        {
            decimal namugy = time;
            int year = (int)(Math.Floor(namugy / (12 * 31 * 86400)));
            namugy = namugy - (year * (12 * 31 * 86400));
            int mon = (int)(Math.Floor(namugy / (31 * 86400)));
            namugy = namugy - (mon * (31 * 86400));
            int day = (int)(Math.Floor(namugy / (86400)));
            namugy = namugy - (day * (86400));
            int hh = (int)(Math.Floor(namugy / 3600));
            namugy = namugy - (hh * 3600);
            int mm = (int)(Math.Floor(namugy / 60));
            namugy = namugy - (mm * 60);
            return year.ToString("00") + "-" + mon.ToString("00") + "-" + day.ToString("00") + " " + hh.ToString("00") + ":" + mm.ToString("00") + ":" + namugy.ToString("00");
        }

        /// <summary>
        /// 사운드발생
        /// </summary>
        /// <param name="On"></param>
        /// <param name="primaryscr"></param>
        /// <remarks></remarks>
        public static void Set_Sound(bool On, bool primaryscr)
        {

            log.Add(AR.Log.ETYPE.NORMAL, "Set_Sound(" + On.ToString() + ") Primary=" + primaryscr.ToString());

            //PLC 제어
            if (PUB.CONFIG.alamplc && PUB.masterk.IsOpen())
            {
                if (On)
                {
                    PUB.log.Add(AR.Log.ETYPE.NORMAL, "DispCtrl1.RaiseAlarm ON");
                    if (PUB.masterk.isValid)
                        PUB.masterk.SetOutput(PUB.CONFIG.plc_addr, true);
                    else
                        PUB.log.Add("ERROR", "plc상태가 유효하지 않습니다 Alarm-ON실패");
                }
                else
                {
                    PUB.log.Add(AR.Log.ETYPE.NORMAL, "DispCtrl1.RaiseAlarm OFF");
                    if (PUB.masterk.isValid)
                        PUB.masterk.SetOutput(PUB.CONFIG.plc_addr, false);
                    else
                        PUB.log.Add("ERROR", "plc상태가 유효하지 않습니다 Alarm-OFF실패");
                }
            }


            //어느화면에서 알람을 발생시켰는지 확인한다
            if (primaryscr)  RaiseSound1 = On;
            else RaiseSound2 = On;

            if (On) ////알람을 켜라
            {
                if (CONFIG.sound)
                {
                    ////
                    if (!RaiseSound) ////소리가 아에 꺼져있다면
                    {

                        //if (System.Diagnostics.Debugger.IsAttached == false)
                        //{
                        var filePath = UTIL.MakePath("sound", "alarm.wav");
                        if (System.IO.File.Exists(filePath))
                        {
                            if (mplayer == null)
                            {
                                mplayer = new MediaPlayer
                                {
                                    Volume = 1.0
                                };
                                mplayer.MediaOpened += (s1, e1) =>
                                {
                                    Console.WriteLine("MediaOpened");
                                    //if (RaiseSound)
                                    {
                                        mplayer.Position = new TimeSpan(0);
                                        mplayer.Play();
                                    }
                                };
                                mplayer.MediaEnded += (s1, e1) =>
                                {
                                    if (System.Diagnostics.Debugger.IsAttached)
                                        Console.WriteLine("MediaEnded");
                                    if (RaiseSound)
                                    {
                                        mplayer.Position = new TimeSpan(0);
                                        mplayer.Play();
                                    }
                                };
                                mplayer.Open(new Uri(filePath));
                            }
                            else
                            {
                                // WAV 파일 재생
                                mplayer.Position = new TimeSpan(0);
                                mplayer.Play();
                            }

                            RaiseSound = true;
                        }
                        else
                        {
                            //파일이 없다면 오류로 한다.
                        }
                    }
                }
                else
                {
                    PUB.log.AddAT($"알람발생조건이지만 환경설정에서 사운드OFF함");
                }
            }
            else ////알람을 꺼라
            {

                if (CONFIG.sound) ////소리를 사용할경우 ..알람이 하나라도 켜져잇다면 울리지 않는다.
                {
                    if (RaiseSound1 == false && RaiseSound2 == false)
                    {
                        if (mplayer != null) mplayer.Stop();
                        RaiseSound = false;
                    }
                }
                else ////소리사용하지않음이라면 오디오를 꺼라
                {
                    try
                    {
                        if (mplayer != null) mplayer.Stop();
                        RaiseSound = false;
                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }

        public static void SaveGroupClass(HMI.CGROUP[] grous, System.IO.FileInfo fi)
        {
            ////그룹정보를 파일로 직렬화저장
            try
            {
                if (fi.Directory.Exists == false) fi.Directory.Create();
                System.IO.FileStream fs2 = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Create);
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf2 = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                bf2.Serialize(fs2, grous);
                fs2.Close();
                PUB.log.Add(AR.Log.ETYPE.NORMAL, "그룹정보파일 저장완료");
            }
            catch (Exception ex)
            {
                PUB.log.Add(AR.Log.ETYPE.ERROR, "그룹정보파일 저장실패:" + ex.Message.ToString());
                //MsgBox(ex.ToString, MsgBoxStyle.Critical, "save fial")
            }
        }
        public static void RunMonitor()
        {
            if (PUB.sm.Step == COMM.ESMStep.RUN)
            {
                PUB.log.Add(AR.Log.ETYPE.NORMAL, "모니터링을 중지하는중");
                PUB.workmsg("모니터링을 중지하는중...");
                DateTime sd = DateTime.Now;
                PUB.sm.SetNewStep(COMM.ESMStep.IDLE);
                PUB.workmsg("");
            }
            else
            {
                PUB.log.Add(AR.Log.ETYPE.NORMAL, "모니터링을 시작하는중");
                PUB.workmsg("Check FreeSpace...");
                PUB.CheckFreeSpace();
                PUB.workmsg("모니터링을 시작하는중...");
                PUB.sm.SetNewStep(COMM.ESMStep.RUN);
                PUB.workmsg("");
            }
        }
        /// <summary>
        /// 구 설정파일 config.xml 을 setting.xml 로 변경 합니다.
        /// </summary>
        public static bool SettingMigration()
        {
            var fiO = new System.IO.FileInfo("config.xml");
            if (fiO.Exists == false) return false;

            var fiN = new System.IO.FileInfo("setting.xml");
            XDocument doc = null;
            try
            {
                doc = XDocument.Load(fiO.FullName);
            }
            catch (Exception ex)
            {
                PUB.log.AddE(ex.Message);
                return false;
            }

            var root = doc.Root;

            PUB.CONFIG.MaxChCount = root.GetData("config", "MaxChCount", "0").toInt();
            PUB.CONFIG.meas_pri1 = root.GetData("config", "meas_pri1", "0").toInt();
            PUB.CONFIG.meas_pri2 = root.GetData("config", "meas_pri2", "0").toInt();
            PUB.CONFIG.meas_sec1 = root.GetData("config", "meas_sec1", "0").toInt();
            PUB.CONFIG.meas_sec2 = root.GetData("config", "meas_sec2", "0").toInt();
            PUB.CONFIG.meas_3rd1 = root.GetData("config", "meas_3rd1", "0").toInt();
            PUB.CONFIG.meas_3rd2 = root.GetData("config", "meas_3rd2", "0").toInt();
            PUB.CONFIG.meas_4th1 = root.GetData("config", "meas_4th1", "0").toInt();
            PUB.CONFIG.meas_4th2 = root.GetData("config", "meas_4th2", "0").toInt();

            PUB.CONFIG.grp0chlist = root.GetData("config", "grp0chlist", "0");
            PUB.CONFIG.grp1chlist = root.GetData("config", "grp1chlist", "0");
            PUB.CONFIG.grp2chlist = root.GetData("config", "grp2chlist", "0");
            PUB.CONFIG.grp3chlist = root.GetData("config", "grp3chlist", "0");
            PUB.CONFIG.grp4chlist = root.GetData("config", "grp4chlist", "0");
            PUB.CONFIG.grp5chlist = root.GetData("config", "grp5chlist", "0");
            PUB.CONFIG.grp6chlist = root.GetData("config", "grp6chlist", "0");

            ////트렌드뷰용 데이터정보
            PUB.CONFIG.maintv_xgap = root.GetData("maintv", "xgap").toInt();
            PUB.CONFIG.maintv_xterm = root.GetData("maintv", "xterm").toInt();
            PUB.CONFIG.maintv_ygap = root.GetData("maintv", "ygap").toFloat();
            PUB.CONFIG.maintv_winsize = root.GetData("maintv", "winsize").toInt();

            ////셀 정보
            PUB.CONFIG.cell_voltindex = root.GetData("rtlview", "voltindex").toInt();
            PUB.CONFIG.cell_timeindex = root.GetData("rtlview", "timeindex").toInt();

            //////트렌드뷰용 데이터정보
            //PUB.CONFIG.tv_fontx = root.GetData("tview", "xfont");
            //PUB.CONFIG.tv_xterm = root.GetData("tview", "xterm").toInt();
            //PUB.CONFIG.tv_yfont = root.GetData("tview", "yfont");
            //PUB.CONFIG.tv_ymax = root.GetData("tview", "ymax").toInt();
            //PUB.CONFIG.tv_ygap = root.GetData("tview", "yterm").toInt();
            //PUB.CONFIG.tv_fontm = root.GetData("tview", "mfont");
            //PUB.CONFIG.tv_colorm = root.GetData("tview", "mcolor").toInt();
            //PUB.CONFIG.tv_marginl = root.GetData("tview", "xmargin").toInt();
            //PUB.CONFIG.tv_margint = root.GetData("tview", "ymargin").toInt();

            ////일반설정
            PUB.CONFIG.tvr_selectgroup0 = root.GetData("trendview", "selectgroup0").toInt();
            PUB.CONFIG.tvr_selectgroup = root.GetData("trendview", "selectgroup").toInt();
            PUB.CONFIG.plc_port = root.GetData("plc", "port");
            PUB.CONFIG.plc_addr = root.GetData("plc", "addr", "0").toInt();
            //PUB.CONFIG.tvr_fontx = root.GetData("tviewr", "xfont");
            //PUB.CONFIG.tvr_xterm = root.GetData("tviewr", "xterm").toInt();
            //PUB.CONFIG.tvr_yfont = root.GetData("tviewr", "yfont");
            //PUB.CONFIG.tvr_ymax = root.GetData("tviewr", "ymax").toInt();
            //PUB.CONFIG.tvr_ygap = root.GetData("tviewr", "yterm").toInt();
            //PUB.CONFIG.tvr_fontm = root.GetData("tviewr", "mfont");
            //PUB.CONFIG.tvr_colorm = root.GetData("tviewr", "mcolor").toInt();
            //PUB.CONFIG.tvr_marginl = root.GetData("tviewr", "xmargin").toInt();
            //PUB.CONFIG.tvr_margint = root.GetData("tviewr", "ymargin").toInt();

            ////일반설정
            PUB.CONFIG.tvr_selectgroup0 = root.GetData("trendviewr", "selectgroup0").toInt();
            PUB.CONFIG.tvr_selectgroup = root.GetData("trendviewr", "selectgroup").toInt();
            PUB.CONFIG.win1pos = root.GetData("config", "win1pos");
            PUB.CONFIG.win2pos = root.GetData("config", "win2pos");
            PUB.CONFIG.databasefolder = root.GetData("config", "dbpath");
            //PUB.CONFIG.autorun = (root.GetData("config", "autorun", "1") == "0") ? false : true;
            PUB.CONFIG.binarysave = (root.GetData("config", "savedb", "0") == "0") ? false : true;
            PUB.CONFIG.synctime = (root.GetData("config", "synctime", "0") == "0") ? false : true;
            PUB.CONFIG.seconddata = (root.GetData("config", "seconddata", "0") == "0") ? false : true;
            PUB.CONFIG.thirddata = (root.GetData("config", "thirddata", "0") == "0") ? false : true;
            PUB.CONFIG.getdata4 = (root.GetData("config", "getdata4", "0") == "0") ? false : true;
            PUB.CONFIG.EnableKA = (root.GetData("config", "EnableKA", "0") == "0") ? false : true;
            PUB.CONFIG.lsb = (root.GetData("config", "lsb", "0") == "0") ? false : true;
            PUB.CONFIG.trashper = short.Parse(root.GetData("config", "trashper", "30")); ////기본30%
            PUB.CONFIG.saveterm = short.Parse(root.GetData("config", "saveterm", "2"));
            PUB.CONFIG.sound = (root.GetData("config", "sound", "1") == "0") ? false : true;

            PUB.CONFIG.dbtype = root.GetData("config", "dbtype", "gdb");
            PUB.CONFIG.viewSize = root.GetData("config", "viewsize", "300").toInt();
            PUB.CONFIG.datadiv = System.Convert.ToInt32(root.GetData("config", "datadiv", "1"));
            PUB.CONFIG.nullbalnce = (root.GetData("config", "nullbalnce", "1") == "0") ? false : true;
            PUB.CONFIG.Sumab = (root.GetData("config", "sumab", "0") == "0") ? false : true;
            PUB.CONFIG.alamplc = (root.GetData("config", "alarmplc", "0") == "0") ? false : true;

            PUB.DESIGN.font_nb = root.GetData("config", "nbfont", "Arial,30,1");
            PUB.DESIGN.font_cellname = "Tahoma,7,1";
            PUB.DESIGN.font_cellvalue = "Tahoma,8,1";

            ////그래프설정
            PUB.CONFIG.graph_time_day = root.GetData("config", "graph_time_day", "0").toInt();
            PUB.CONFIG.graph_time_hour = root.GetData("config", "graph_time_hour", "0").toInt();
            PUB.CONFIG.graph_time_min = root.GetData("config", "graph_time_min", "45").toInt();
            PUB.CONFIG.graph_line_width = root.GetData("config", "graph_line_width", "1").toInt();
            PUB.CONFIG.graph_starty = root.GetData("config", "graph_starty", "0").toInt();
            PUB.CONFIG.graph_endy = root.GetData("config", "graph_endy", "5").toInt();
            PUB.CONFIG.graph_line_width = root.GetData("config", "graph_line_width", "1").toInt();

            fiO.MoveTo("config_migration.xml");
            PUB.log.Add("setting migration complete");
            PUB.CONFIG.AfterLoad();
            PUB.CONFIG.Save();

            return true;
        }



        public static void INIT(out List<string> errormessages)
        {
            errormessages = new List<string>();
            var errorlist = new List<string>();
            log = new AR.Log();//.ArinLog();

            StatusMSG("Reading Configuration");

            CONFIG = new CSetting(); ////설정파일 초기화  150319
            CONFIG.Load();

            DESIGN = new CDesignSetting();
			DESIGN.filename = new System.IO.FileInfo("DesignSetting.xml").FullName;
            DESIGN.Load();

            TREND = new CTrendSetting();
            TREND.filename = new System.IO.FileInfo("TrendSetting.xml").FullName;
            TREND.Load();

            SettingMigration();

            ////설정정보가져오기
            workmsg("Read Setting");

            ////master-K 231120  chi
            masterk = new arDev.MasterK();

            indicator = new DigitalIndicator();

            ////init Folder
            workmsg("Init Dir");

            if (UTIL.IsDriveValid(CONFIG.GetDatabasePath()) == false)
            {
                errorlist.Add($"저장경로의 드라이브가 유효하지 않아 임시경로로 변경 됩니다\n" +
                          $"전:{CONFIG.GetDatabasePath()}\n" +
                          $"후:{UTIL.CurrentPath}");
                CONFIG.databasefolder = UTIL.CurrentPath;
            }
            if (System.IO.Directory.Exists(CONFIG.GetDatabasePath()) == false)
            {
                try
                {
                    System.IO.Directory.CreateDirectory(CONFIG.GetDatabasePath());
                    errorlist.Add($"저장경로 신규생성\n{CONFIG.GetDatabasePath()}");
                }
                catch (Exception ex)
                {
                    //CONFIG.GetDatabasePath() = UTIL.CurrentPath;
                    errorlist.Add($"저장경로 생성실패\n{CONFIG.GetDatabasePath()}\n{ex.Message}");
                }
            }


            DB = new CFDB(CONFIG.GetDatabasePath(), "Database", "volt");
            Alarm = new CFDBA(CONFIG.GetDatabasePath(), "Database", "Alarm");
            KADB = new CFDBK(CONFIG.GetDatabasePath(), "Database", "Ka"); ////ka 전용데이터베이스 150310

            ////측정용 폴더 만들기
            var pathBin = Path.Combine(CONFIG.GetDatabasePath(), "MeasureData", "Binary");
            if (Directory.Exists(pathBin) == false)
            {
                Directory.CreateDirectory(pathBin);
                errorlist.Add($"측정데이터(Binary) 폴더생성\n{pathBin}");
            }


            var pathAsc = Path.Combine(CONFIG.GetDatabasePath(), "MeasureData", "Ascii");
            if (Directory.Exists(pathAsc) == false)
            {
                Directory.CreateDirectory(pathAsc);
                errorlist.Add($"측정데이터(Asc) 폴더생성\n{pathAsc}");
            }


            log.Add(AR.Log.ETYPE.NORMAL, "설정읽어오기완료");

            ////파라미터를 이용해서 설정모드로 들어왔다면
            if (setupmode)
            {
                var f = new Frm_Config();
                f.ShowDialog();
                Application.Exit();
            }
            else
            {
                //If Not lb Is Nothing Then lb.Text = "장치를 초기화하는중..."
                StatusMSG("Check MACHINE(DA100)");
                workmsg("Check MACHINE(DA100)");

                ////설정정보를 가져온다.
                //List<string> errorlist = new List<string>();
                System.Threading.Tasks.Task task = Task.Factory.StartNew(() =>
                {
                    string[] BackTables = new string[] { "DEVICE", "GRP", "NORMAL", "WIN", "VIEWGROUP", "CHANNEL", "VIEWGROUPR" };
                    foreach (string tabname in BackTables)
                    {
                        var fname = System.IO.Path.Combine(CONFIG.GetDatabasePath(), "Database", "Config", $"{tabname}.xml");
                        var fn = new System.IO.FileInfo(fname);
                        if (fn.Exists)
                        {
                            PUB.DS.Tables[tabname].ReadXml(fn.FullName);
                            PUB.log.Add($"Load File({tabname}) : {fn.FullName}");
                        }
                        else if (tabname.StartsWith("VIEWGROUP") == false)
                            errorlist.Add($"설정파일없음\n{tabname}");
                    }
                });
                task.Wait();

                ////회사정보가 없으면 저장한다.
                if (PUB.DS.NORMAL.Rows.Count == 0)
                {
                    var newnnr = PUB.DS.NORMAL.NewNORMALRow();
                    newnnr.IDX = 1;
                    newnnr.ALAMH = 0;
                    newnnr.ALAML = 0;
                    PUB.DS.NORMAL.AddNORMALRow(newnnr);
                    errorlist.Add($"등록된 회사 정보가 없어 신규로 생성 했습니다.");
                }

                ////사용가능한 장치의 갯수
                int Devicecount = PUB.DS.DEVICE.Where(t => t.USE == 1).Count();//.Select("use=1").Length; //  DBC.GetScalar("Select count(*) from DEVICE where USE=1 ")
                DAQ = new CMachine[Devicecount - 1 + 1];

                var Drs = PUB.DS.DEVICE.Where(t => t.USE == 1).OrderBy(t => t.IDX);
                int idx = 0;
                foreach (var dr in Drs)
                {
                    log.Add(AR.Log.ETYPE.NORMAL, $"connecting DAQ {dr.IP}:{dr.PORT}");
                    DAQ[idx] = new GM10(dr.IP, dr.PORT, dr.TITLE, dr.CHCOUNT, dr.IDX);
                    DAQ[idx].idx = (short)idx;
                    StatusMSG($"Make Device {dr.IP}");
                    idx++;
                }
            }

            workmsg("");
            StatusMSG("Initializing OK");
            if (errorlist.Any()) errormessages.AddRange(errorlist);
        }

        public static void StatusMSG(string m)
        {
            PUB.RaiseRemoteCommandEvent(rCommand.StateMessage, m);
        }

        public static void CheckFreeSpace()
        {
            return;
            //			pub.log.Add(AR.Log.ETYPE.NORMAL, "남은공간체크");
            //			char drv = pub.CONFIG.databasefolder.Substring(0, 1);
            //			foreach (System.IO.DriveInfo d in (new Microsoft.VisualBasic.Devices.ServerComputer()).FileSystem.Drives)
            //			{
            //				char drv2 = d.Name.Substring(0, 1);
            //				if (drv2 == drv)
            //				{
            //					double freerate = System.Convert.ToDouble(System.Convert.ToInt32((double) d.AvailableFreeSpace / d.TotalSize) * 100);
            //					this.lb_diskfree.Text = "<FreeSpace(" + System.Convert.ToString(drv) + "):" + freerate.ToString("#0.0") + "%>";
            //					if ((short) freerate < pub.CONFIG.trashper) ////남은공간비율이  지정한 비율보다 낮으면 자료의 삭제처리를 한다 엣날꺼부터
            //					{
            //						this.lb_diskfree.ForeColor = Color.Red;
            ////날짜별로 폴더를 정리하고 가장 오래된 날짜 1일을 제거한다.
            //						List<string> DateList = pub.DB.GetDateList();
            //						if (DateList.Count > 0)
            //						{
            //							System.IO.DirectoryInfo DelDir = new System.IO.DirectoryInfo(DateList[0]);
            //							try
            //							{
            //								DelDir.Delete(true);
            //								pub.log.Add("디스크정리:" + DelDir.FullName);
            //								}
            //								catch (Exception ex)
            //								{
            //									pub.log.Add(AR.Log.ETYPE.ERROR, "디스크정리실패:" + ex.Message);
            //									}
            //									}
            //									}
            //									else
            //									{
            //										this.lb_diskfree.ForeColor = Color.Black;
            //										}
            //										}
            //										}
        }

    }
}
