using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using GcDevicePc.IniParam;

namespace GcDevicePc
{
    public delegate void AUXTool(int flag, ushort futime, ushort hvtime);
    public delegate void StopForUpdateFirm();
    public delegate void UpdateFirmCMD();
    public delegate void SetPos(int ipos, string vinfo);
    public delegate void TCD_SW(ushort port);
    public delegate void TCD_SetDAC(ushort port, ushort val);

    public delegate void HAir_SW(int val);

    public partial class auxtool : Form
    {
        private string HmiIP = null;
        private ushort HmiPort = 911;
        private ArrayList SearchRet = new ArrayList();

        public auxtool()
        {
            InitializeComponent();
        }

        public auxtool(ushort time1, ushort time2)
        {
            InitializeComponent();

            this.fireuptime.Text = time1.ToString();
            this.hvalvetime.Text = time2.ToString();
        }

        public void setfireuptime(ushort time1, ushort time2)
        {
            this.fireuptime.Text = time1.ToString();
            this.hvalvetime.Text = time2.ToString();
        }

        private void SetTextMesssage(int ipos, string vinfo)
        {
            if (this.InvokeRequired)
            {
                SetPos setpos = new SetPos(SetTextMesssage);
                this.Invoke(setpos, new object[] { ipos, vinfo });
            }
            else
            {
                this.label4.Text = ipos.ToString() + "/100";
                this.progressBar1.Value = Convert.ToInt32(ipos);          

                if(ipos == 100 || send_ok)
                {
                    this.label4.Text = "传输完成";
                    this.runbtn.Enabled = true;
                    this.chosenbtn.Enabled = true;
                    this.updatebtn.Enabled = true;   
                }
            }
        }

        private void hvalvetime_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }

        private void fireuptime_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }

        public event AUXTool auxtoolforfireup;
        private void fireupbtn_Click(object sender, EventArgs e)
        {
            if(String.IsNullOrEmpty(fireuptime.Text) || String.IsNullOrEmpty(hvalvetime.Text))
            {
                MessageBox.Show("点火时间 和 氢气阀时间不能为空！！！");
            }
            else
            {
                ushort time1 = ushort.Parse(fireuptime.Text);
                ushort time2 = ushort.Parse(hvalvetime.Text);

                if(time1 >= time2)
                {
                    auxtoolforfireup(0, time1, time2);
                }else
                {
                    MessageBox.Show("点火时间需大于等于氢气阀时间！！！");
                }  
            }
        }

        private string updateexe = null;
        private string localpath = null;
        private void CHmibtn_Click(object sender, EventArgs e)
        {
            if (HmiIP != null)
            {
                if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == false)
                {
                    this.CHmibtn.Enabled = false;
                    int ret = 0;
                    FileServerClient singlesend = new FileServerClient();
                    singlesend.WtClientInit(HmiIP, HmiPort);
                    ret = singlesend.WtHMICloseRro("WtMainProc");
                    if(ret == 1)
                    {
                        MessageBox.Show("停止系统成功！");
                    }

                    singlesend.WtClientClose();
                   // this.runbtn.Enabled = true;
                    this.chosenbtn.Enabled = true;
                    this.updatebtn.Enabled = true;
                    
                }else
                {
                    MessageBox.Show("请停止系统，再关闭！");
                }

               
            }           
        }

        private void runbtn_Click(object sender, EventArgs e)
        {
            int ret;
            if (HmiIP != null)
            {
                FileServerClient singlesend = new FileServerClient();
                singlesend.WtClientInit(HmiIP, HmiPort);
                ret = singlesend.WtHMIRunPro("GcDevice.exe", globaldata.exeremoteFolder);
                if (ret == 1)
                {
                    MessageBox.Show("开启系统成功！");
                }
                singlesend.WtClientClose();

                this.runbtn.Enabled = false;
                this.chosenbtn.Enabled = false;
                this.updatebtn.Enabled = false;
                this.CHmibtn.Enabled = true;

                this.label4.Text = "";
                this.progressBar1.Value = 0;
                this.ProName.Text = "";
            }
        }

        private void chosenbtn_Click(object sender, EventArgs e)
        {
            string file;
            OpenFileDialog fileDlg = new OpenFileDialog();
            fileDlg.Multiselect = false;
            fileDlg.InitialDirectory = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.TmpFolder;
            fileDlg.RestoreDirectory = true;
            fileDlg.Title = "请选择方法文件";
            fileDlg.Filter = "更新程序(*.*)|*.*";
            if (fileDlg.ShowDialog() == DialogResult.OK)
            {
                file = fileDlg.FileName;
                this.updateexe = file.Substring(file.LastIndexOf("\\") + 1);
                this.localpath = file;
                this.ProName.Text = this.localpath;
                this.updatebtn.Enabled = true;

            }
        }

        private void updatebtn_Click(object sender, EventArgs e)
        {
            if (HmiIP != null)
            {
                this.CHmibtn.Enabled = false;
                this.runbtn.Enabled = false;
                this.chosenbtn.Enabled = false;
                this.updatebtn.Enabled = false;


                Thread fThread = new Thread(new ThreadStart(SleepT));
                fThread.IsBackground = true;
                fThread.Start();
            }
        }

        private bool send_ok = false;
        private void SleepT()
        {
            Thread send_Thread = new Thread(new ThreadStart(sendnewhmi));
            send_Thread.IsBackground = true;
            send_Thread.Start();

            for (int i = 0; i < 100; i++)
            {
                if(send_ok)
                {
                    SetTextMesssage(100, i.ToString() + "\r\n");
                }else
                {
                    Thread.Sleep(200);
                    SetTextMesssage(i, i.ToString() + "\r\n");

                    if(i == 95)
                    {
                        i--;
                    }

                }               
            }       
        }

        private void sendnewhmi()
        {
            int ret;
            FileServerClient singlesend = new FileServerClient();
            singlesend.WtClientInit(HmiIP, HmiPort);
            ret = singlesend.WtClientCopytoServerNoDelay(this.updateexe, this.localpath, globaldata.exeremoteFolder);

            if (ret == 1)
            {
                this.send_ok = true;
            }

            singlesend.WtClientClose();
        }


        bool hmisearch = false;
        Thread addhmi;
        ManualResetEvent mre = new ManualResetEvent(false);
        private void searchHMI_Click(object sender, EventArgs e)
        {
            ArrayList DeviceList = new ArrayList();
            if(!hmisearch)
            {
                if(mre != null)
                    mre.Reset();
                addhmi = new Thread(searchhmi);
                addhmi.IsBackground = true;
                addhmi.Start();             
                this.searchHMI.Text = "停止";              
                hmisearch = !hmisearch;
            }
            else
            {           
                this.searchHMI.Text = "搜索";           
                this.hmilist.Text = "请选择...";        
                mre.Set();
                hmisearch = !hmisearch;
            }         
        }

        private void searchhmi()
        {
            ProThread.HMISearch mysearch = new ProThread.HMISearch(null);
            int hmicount = 0 ;
            int i;
            mysearch.ThStart();
            while (!mre.WaitOne(500))
            {             
                hmicount = mysearch.HMICount();

                this.Invoke(new Action(() =>
                {
                    this.hmilist.Text = "搜索到" + hmicount + "个";
                }));
            }

            this.Invoke(new Action(() =>
            {
                hmilist.Items.Clear();
                //SearchRet = globaldata.hHMIList;  
                SearchRet = mysearch.myHMIList;
                for (i = 0; i < hmicount; i++)
                {
                    hmilist.Items.Add(((globaldata.DeviceInfo)(SearchRet[i])).IpAddr);
                }
            }));             
            mysearch.ThStop();
        }

        private void hmilist_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.HmiIP = this.hmilist.Text;

            this.CHmibtn.Enabled = true;
        }

        private void auxtool_Load(object sender, EventArgs e)
        {
            this.CHmibtn.Enabled = false;
            this.runbtn.Enabled = false;
            this.chosenbtn.Enabled = false;
            this.updatebtn.Enabled = false;
        }

        public event StopForUpdateFirm sfupdatefirm;
        public event UpdateFirmCMD updatefirm;
        private void firmwareupdate_Click(object sender, EventArgs e)
        {
            if (HmiIP != null)
            {
                sfupdatefirm();
                this.label7.Text = "发送中...";
                Thread fThread = new Thread(new ThreadStart(FirmWareUpdate));
                fThread.IsBackground = true;
                fThread.Start();

            }
        }


        private bool updatefirm_ok = false;
        private bool sendfirm_ok = false;
        private void FirmWareUpdate()
        {
            Thread send_Thread = new Thread(new ThreadStart(sendfirmware));
            send_Thread.IsBackground = true;
            send_Thread.Start();

            for (int i = 0; i < 100; i++)
            {
                if (updatefirm_ok)
                {
                    SetTextMesssage2(100, i.ToString() + "\r\n");
                }
                else
                {
                    Thread.Sleep(500);
                    SetTextMesssage2(i, i.ToString() + "\r\n");

                    if (i == 95)
                    {
                        i--;
                    }

                }
            }
        }

        private void sendfirmware()
        {
            string firmDire = null;
            string fullfilename = null;
            bool updatestart = false;
            firmDire = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.FwFolder;

            //try
            //{
                FileServerClient singlesend = new FileServerClient();
                DirectoryInfo theFolder = new DirectoryInfo(firmDire);
                DirectoryInfo[] dirInfo = theFolder.GetDirectories();

                singlesend.WtClientInit(HmiIP, HmiPort);
                foreach (FileInfo NextFile in theFolder.GetFiles())
                {
                    fullfilename = NextFile.FullName;
                    singlesend.WtClientCopytoServerNoDelay(NextFile.Name, fullfilename, globaldata.updateremoteFolder);
                    Thread.Sleep(500);
                }
               
                sendfirm_ok = true;
                singlesend.WtClientClose();

                if (sendfirm_ok)
                {
                    updatefirm();

                    while(true)
                    {
                        if (globaldata.m_hmibuffer.gcinfo.hmistatus == 5)
                        {

                            this.Invoke(new Action(() =>
                            {
                                this.label7.Text = "更新中...";
                            }));
                            updatestart = true;
                        }

                        if( updatestart)
                        {
                            if (globaldata.m_hmibuffer.gcinfo.hmistatus == 0)
                            {
                                this.Invoke(new Action(() =>
                                {
                                    this.label7.Text = "更新完成...";
                                }));

                                updatefirm_ok = true;
                                sendfirm_ok = false;
                                break;
                            }
                        }

                        Thread.Sleep(500);
                    }
                }  
        }

        private void SetTextMesssage2(int ipos, string vinfo)
        {
            if (this.InvokeRequired)
            {
                SetPos setpos = new SetPos(SetTextMesssage2);
                this.Invoke(setpos, new object[] { ipos, vinfo });
            }
            else
            {
                this.label6.Text = ipos.ToString() + "/100";
                this.progressBar2.Value = Convert.ToInt32(ipos);

                if (ipos == 100)
                {
                    this.label7.Text = "更新完成...";
                }
            }
        }

        public event HAir_SW hairsw;
        private void hair_h1_Click(object sender, EventArgs e)
        {
            hairsw(1);
        }

        private void hair_a1_Click(object sender, EventArgs e)
        {
            hairsw(2);
        }

        private void hair_h2_Click(object sender, EventArgs e)
        {
            hairsw(3);
        }

        private void hair_a2_Click(object sender, EventArgs e)
        {
            hairsw(4);
        }


    }
}
