using JWH;
using System;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace DDUtilityApp
{

    public class GlobalVariable
    {

        [ReadOnly(true)]
        public static GlobalVariable Instance { get; set; } = new GlobalVariable();

        /// <summary>
        /// 설정정보 파일 경로
        /// </summary>
        public string DefaultPath { get; set; }

        /// <summary>
        /// 로그파일 다운로드 경로
        /// </summary>
        public string DownloadPath { get; set; }

        /// <summary>
        /// 로그파일 다운로드 경로 jhlim 20250202
        /// </summary>
        public string MesDownloadPath { get; set; }

        /// <summary>
        /// Workflow 다운로드 경로
        /// </summary>
        public string WorkflowPath { get; set; }

        /// <summary>
        /// Workflow(Compress) 원본파일 경로 구분
        /// </summary>
        public string WorkflowLocation { get; set; } = "Remote";

        /// <summary>
        /// Workflow(Compress) 원본파일 경로
        /// </summary>
        public string WorkflowCompressPath { get; set; }

        public FormStartPosition FormStartPosition { get; set; } = FormStartPosition.CenterScreen;

        public FormWindowState FormWindowState { get; set; } = FormWindowState.Maximized;

        public Point FormLocation { get; set; } = new Point(0, 0);

        public Size FormSize { get; set; } = new Size(1300, 750);

        #region [ LogParser ]

        public string EisParser_GridHeader { get; set; } = string.Empty;

        public string AgvParser_GridHeader { get; set; } = string.Empty;

        #endregion

        #region [ FrmEqSelector ]

        /// <summary>
        /// EquipmentSelector 설비명 표시 필드. DDUtilityName;Description;MesName;
        /// </summary>
        public string FrmEqSelector_NameOrder { get; set; } = "MesName;DDUtilityName;Description;";

        public bool FrmEqSelector_AllEquipment { get; set; } = false;

        public bool FrmEqSelector_UseMesDB { get; set; } = false;

        public string FrmEqSelector_GridEquipmentHeader { get; set; } = string.Empty;

        public bool FrmEqSelector_UseSMB { get; set; } = false;

        #endregion

        public GlobalVariable()
        {
            this.LodConfig();
            this.LoadSetting();

            if (string.IsNullOrEmpty(this.FrmEqSelector_GridEquipmentHeader))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append($"Facility;");
                sb.Append($"Line;");
                sb.Append($"EquipmentID;");
                sb.Append($"DisplayName;");
                //sb.Append($"ControlMode;");
                //sb.Append($"State;");
                sb.Append($"ModelID;");
                sb.Append($"Version;");
                sb.Append($"EquipmentIP;");
                sb.Append($"Port;");
                sb.Append($"ServerIP;");
                sb.Append($"GemSettingID;");
                sb.Append($"DriverFileName;");
                this.FrmEqSelector_GridEquipmentHeader = sb.ToString();
            }
        }

        private void LodConfig()
        {
            // DefaultPath
            string defaultPath = ConfigurationManager.AppSettings["DefaultPath"];
            if (string.IsNullOrEmpty(defaultPath)) defaultPath = $@"%MyDocuments%\DDUtility\";
            this.DefaultPath = defaultPath.Replace("%MyDocuments%", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            this.DownloadPath = $@"{this.DefaultPath}Download\";
            this.WorkflowPath = $@"{this.DefaultPath}Workflow\";
            this.MesDownloadPath = $@"{this.DefaultPath}MesDownload\";   //jhlim 20250202
        }

        public void LoadSetting()
        {
            this.LoadSetting($@"{this.DefaultPath}Setting.xml");
        }

        private void LoadSetting(string filename)
        {
            try
            {
                Type type = this.GetType();

                XmlDocument document = new XmlDocument();
                document.Load(filename);

                PropertyInfo property = null;
                foreach (XmlNode node in document.GetNodesByName("Property"))
                {
                    try
                    {
                        property = type.GetProperty(node.Attributes["NAME"].Value);
                        string strValue = node.Attributes["VALUE"].Value;
                        if (property == null) continue;

                        object value = null;
                        if (property.PropertyType == typeof(System.Type))
                        {
                            value = Type.GetType(strValue);
                        }
                        else if (property.PropertyType == typeof(Size))
                        {
                            string[] splitValues = strValue.Split(new string[] { "{", "}", "=", "," }, StringSplitOptions.RemoveEmptyEntries);
                            value = new Size(int.Parse(splitValues[1]), int.Parse(splitValues[3]));
                        }
                        else if (property.PropertyType == typeof(Point))
                        {
                            string[] splitValues = strValue.Split(new string[] { "{", "}", "=", "," }, StringSplitOptions.RemoveEmptyEntries);
                            value = new Point(int.Parse(splitValues[1]), int.Parse(splitValues[3]));
                        }
                        else
                        {
                            value = TypeDescriptor.GetConverter(property.PropertyType).ConvertFrom(strValue);
                        }

                        property.SetValue(this, value);
                    }
                    catch (Exception ex)
                    {
                        XLogger.Instance.Fatal($"{property.Name}", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        public void SaveSetting()
        {
            this.SaveSetting($@"{this.DefaultPath}Setting.xml");
        }

        private void SaveSetting(string filename)
        {
            try
            {
                Type type = this.GetType();

                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"<DDUtility>");
                sb.AppendLine($"  <Properties>");
                foreach (PropertyInfo property in type.GetProperties())
                {
                    Attribute attribute = property.GetCustomAttribute(typeof(ReadOnlyAttribute));
                    if (attribute != null && ((ReadOnlyAttribute)attribute).IsReadOnly) continue;

                    object value = property.GetValue(this);
                    sb.AppendLine($"    <Property NAME='{property.Name}' VALUE='{value}' />");
                }
                sb.AppendLine($"  </Properties>");
                sb.AppendLine($"</DDUtility>");

                using (StreamWriter stream = File.CreateText(filename))
                    stream.Write(sb.ToString());
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

    }

}
