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 AR.Log log;
        public static bool NotExitMonitor = false;
        public static CFDBA Alarm;
        public static CSetting CONFIG;
        public static string lasttime = "";
        public static DocumentElement DS = new DocumentElement();
        public static bool runerror = false; ////실행오류
        public static string lastStatueMessage = "";
        public static System.Text.StringBuilder StartErrmsg = new System.Text.StringBuilder();
        public static int WindowCount = 0;
        public static DateTime StartupTime = DateTime.Now;
        public static string ExtCommand = "";

        public static string GetGrpName(int idx)
        {
            var dr = PUB.DS.GRP.Select("IDX=" + System.Convert.ToString(idx)) as DocumentElement.GRPRow[];
            if (dr.Length != 1)
            {
                return "";
            }
            return dr[0].TITLE;
        }

        public static string GetChannelName(int idx)
        {
            var dr = PUB.DS.CHANNEL.Select("IDX=" + System.Convert.ToString(idx)) as DocumentElement.CHANNELRow[];
            if (dr.Length != 1)
            {
                return "";
            }
            return dr[0].TITLE;
        }
        ////타임정보를 숫자로 반환함
        public static decimal get_TimeNumber(DateTime time)
        {
            return time.Hour * 3600 + time.Minute * 60 + time.Second;
        }
     
        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");
        }

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

         
            CONFIG = new CSetting(); ////설정파일 초기화  150319
            CONFIG.filename = new System.IO.FileInfo("..\\Setting.xml").FullName;
            CONFIG.Load();


            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}");
                }
            }

            Alarm = new CFDBA(CONFIG.GetDatabasePath(), "Database", "Alarm");


            ////설정정보를 가져온다.
            //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}");
                    }
                }
            });
            task.Wait();




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

            if (errorlist.Any()) errormessages.AddRange(errorlist);
        }

     
    }
}
