using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GcDevicePc.Common;
using GcDevicePc.GCBuffer;
using GcDevicePc.ProThread;
using Ini.Net;

namespace GcDevicePc
{
    class AppInit
    {
        private IniFile IniParser;

        /// <summary>
        /// 检测文件和目录是否存在
        /// </summary>
        /// <param name="flag">检测标志 0-表示检测目录</param>
        /// <param name="sPath"></param>
        /// <returns></returns>
        private bool CheckFolderandFile(int flag, string sPath)
        {
            switch (flag)
            {
                case 0:     //检测并创建目录
                    {
                        if (!Directory.Exists(sPath))
                        {
                            Directory.CreateDirectory(sPath);
                        }
                    }
                    break;
                case 1:
                    break;
            }

            return true;
        }

        
        public void InitAppFolder()
        {
            string tmpFolder;
            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.ConfigFolder = System.Windows.Forms.Application.StartupPath;

            tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.ConfigFolder;
            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder = Path.Combine(tmpFolder, "仪器方法");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder = Path.Combine(tmpFolder, "仪器状态");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder = Path.Combine(tmpFolder, "运行表");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder = Path.Combine(tmpFolder, "历史数据");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.FwFolder = Path.Combine(tmpFolder, "固件更新");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.FwFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.TmpFolder = Path.Combine(tmpFolder, "tmpfile");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.TmpFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.LogFolder = Path.Combine(tmpFolder, "Logs");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.LogFolder);

            tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder;
            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.SubStatusFolder = Path.Combine(tmpFolder, "子状态");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.SubStatusFolder);

        }

        public void InitAppFolderGC()
        {
            string tmpFolder;
            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.ConfigFolder = System.Windows.Forms.Application.StartupPath+"\\..\\GC_Config\\GC_Set";

            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.ConfigFolder);

            tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.ConfigFolder;
            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder = Path.Combine(tmpFolder, "仪器方法");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder = Path.Combine(tmpFolder, "仪器状态");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder = Path.Combine(tmpFolder, "运行表");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder = Path.Combine(tmpFolder, "历史数据");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.FwFolder = Path.Combine(tmpFolder, "固件更新");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.FwFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StartUpFolder = Path.Combine(tmpFolder, "启动参数");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StartUpFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.TmpFolder = Path.Combine(tmpFolder, "tmpfile");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.TmpFolder);

            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.LogFolder = System.Windows.Forms.Application.StartupPath + "\\..\\GC_User\\Logs";
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.LogFolder);

            tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder;
            globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.SubStatusFolder = Path.Combine(tmpFolder, "子状态");
            CheckFolderandFile(0, globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.SubStatusFolder);

        }

        public void InitAppDefaultConfig()
        {

            String filefolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.ConfigFolder;

            List<String> foldername = new List<string>
            {
                globaldata.remoteFolder + "仪器方法\\",
                globaldata.remoteFolder + "仪器状态\\",
                globaldata.remoteFolder + "运行表\\"
            };

            List<String> localfoldername = new List<string>
            {
                filefolder + "\\仪器方法\\",
                filefolder + "\\仪器状态\\",
                filefolder+ "\\运行表\\"
            };

            List<String> filename = new List<string>
            {
                "SingleAnal.ini",
                "DevStatus.ini",
                "RunMethod.ini"
            };

            int checkflag = 0;
            int ret = 0;


            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                String checkfile = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder,
                    "DevStatus.ini");
                if (File.Exists(checkfile))
                {
                    IniParser = new IniFile(checkfile);
                    if (!IniParser.KeyExists("仪器编号", "仪器编码") && !IniParser.KeyExists("仪器编号", "仪器名称"))
                    {
                        File.Delete(Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder,
                            "DevStatus.ini"));
                    }
                }

                FileTools filecheck = new FileTools();
                FileServerClient mainclient = new FileServerClient();
                mainclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
                for (int i = 0; i < filename.Count; i++)
                {
                    String getfile = localfoldername[i] + filename[i];
                    checkflag = filecheck.IsUse(getfile);

                    if (checkflag == 0)
                    {
                        continue;
                    }
                    else if (checkflag == 1)
                    {
                        
                        ret = mainclient.WtClientCopyfromServer(filename[i], getfile, foldername[i]);
                        if (ret == 0)
                        {
                            Log.Info(filename[i].ToString() + " 同步成功");
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                mainclient.WtClientClose();
            }

            //单次
            String tmpfile = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder,"SingleAnal.ini");
            IniParser = new IniFile(tmpfile);
            if (IniParser.KeyExists("方法名称", "名称"))
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = IniParser.ReadString("方法名称", "名称");
            else
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = "SingleAnal.ini";

            // BAT
            tmpfile = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder, "RunMethod.ini");
            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab = tmpfile;
            if (!File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab))
            {
                RunTableHelper default_runtable =
                    new RunTableHelper(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder, "RunMethod.ini");
                default_runtable.SaveRunTable();
            }

            IniParser = new IniFile(tmpfile);
            if(IniParser.KeyExists("运行表", "1"))
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName = IniParser.ReadString("运行表", "1");
            else
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName = null;


            tmpfile = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder, "DevStatus.ini");
            if (File.Exists(tmpfile) == false)
            {
                HWConfig default_devstatus = new HWConfig(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder, "DevStatus.ini");
                //default_devstatus.SavaHWConfig();
            }
            else
            {
                globaldata.m_hwconfig.setFileName(tmpfile);
                Console.WriteLine(globaldata.m_hwconfig.hwconfiginfo.GCNum);
            }

            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName = tmpfile;

            tmpfile = null;
        }

        public void LocalNetworkCheck()
        {
            String localip = "";
            while (true)
            {
                try
                {
                    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                    foreach (NetworkInterface adapter in nics)
                    {
                        if (adapter.Name == "本地连接")
                        {
                            bool pd1 = (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
                                        adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211);
                            if (pd1)
                            {
                                IPInterfaceProperties ip = adapter.GetIPProperties();
                                UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses;
                                foreach (UnicastIPAddressInformation ipadd in ipCollection)
                                {
                                    if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
                                        localip = ipadd.Address.ToString();
                                }

                                if (!String.IsNullOrEmpty(localip))
                                {
                                    globaldata.StartNetwork = true;
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e.Message);
                    globaldata.StartNetwork = false;
                }

                if (globaldata.OffLinkMode || globaldata.StartNetwork)
                {
                    break;
                }

                Thread.Sleep(1000);
            }
        }

        public void ConnectionIPInit()
        {
            HMISearch mysearch = new HMISearch(null);
            int hmicount = 0;
            bool ret = false;
            string ip;

            while (true)
            {
                ret = mysearch.ThStart();

                if (ret)
                {
                    Thread.Sleep(3000);
                    hmicount = mysearch.HMICount();
                    if (hmicount >= 1)
                    {
                        ip = (((globaldata.DeviceInfo) (mysearch.myHMIList[0])).IpAddr);
                        globaldata.connection_ip = ip;
                        mysearch.ThStop();
                        break;
                    }

                    mysearch.ThStop();
                }
                else
                {
                    mysearch.ReGetHmiIp();
                    Thread.Sleep(2000);
                }

                if (globaldata.OffLinkMode)
                {
                    globaldata.connection_ip = "";
                    break;
                }
            }
        }

    }
}
