using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace LiveUpdate
{
    /// <summary>
    /// 
    /// </summary>
    public partial class frmStartUpdate : Form
    {
        /// <summary>
        /// 
        /// </summary>
        public frmStartUpdate()
        {
            InitializeComponent();
        }
        private ClsLiveUpdate m_myLiveUpdate;
        /// <summary>
        /// 设置升级
        /// </summary>
        public ClsLiveUpdate T_myLiveUpdate
        {
            get { return m_myLiveUpdate; }
            set { m_myLiveUpdate = value;}
        }
        private int m_isUpdate =1;
        /// <summary>
        /// 是否是在线更新
        /// </summary>
        public int T_isUpdate
        {
            get { return m_isUpdate; }
            set { m_isUpdate = value;}
        }
        private void FrmStartUpdate_Load(object sender, EventArgs e)
        {
            if (m_isUpdate == 1)
            {
                BtnOK.Text = "完成更新";
            }
            else
            {
                BtnOK.Text = "立即安装";
                Text = "正在下载中.....";
                label1.Text = "软件正在下载升级文件,请稍后。。。。\r\n您可以最小化本界面。";
            }
        }
        private void LiveUpdateProgressChanged(object sender, LiveUpdate.LiveUpdateEventArgs e)
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                        progressBar1.Value = Convert.ToInt32(e.CurrProgress);
                        label2.Text = "文件大小:" + ryCommon.RyFiles.GetFileSizeStr(e.CurrentFileSize) + " 已完成:" + e.CurrProgress.ToString("0.00") + "%";
                        Application.DoEvents();
                        if (e.IsCompleted && haveupdate_zip)
                        {
                            if (m_isUpdate == 1)
                            {
                                label1.Text = "升级包下载完毕！请点击“完成更新”按钮进行后续升级。";
                            }
                            else
                            {
                                label1.Text = "软件下载完毕！请点击“立即安装”按钮进行后续升级。";
                            }
                            isRunning = false;
                            BtnOK.Enabled = true;
                            BtnOK.PerformClick();
                        }
                //timer1.Enabled = true;
                }));
                if(e.IsCompleted && last_mainRunning)
                {
                    isRunning = false;
                }
            }
            catch (Exception)
            {
               
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="PramCom"></param>
        /// <returns></returns>
        public int RunFile(string FilePath, string PramCom)
        {
            try
            {
                System.Diagnostics.Process.Start(FilePath, PramCom);
                return 1;
            }
            catch{return 0; }
        }
        /// <summary>
        /// 
        /// </summary>
        public event LiveUpdate.OnAppExit OnAppExit;
        private void BtnOK_Click(object sender, EventArgs e)
        {
            if (m_isUpdate == 1)
            {
                BtnOK.Enabled = false;
                System.IO.File.WriteAllText(Application.StartupPath + "\\tmp.updx", T_myLiveUpdate.UpdateType.sxSettingXML, Encoding.UTF8);
                if (!System.IO.File.Exists(Application.StartupPath + "\\rycUpdate.exe"))
                {
                    BtnOK.Enabled = true;
                    MessageBox.Show("升级程序已被破坏，升级失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                RunFile(Application.StartupPath + "\\rycUpdate.exe", "update");
                OnAppExit?.Invoke(sender, e);
                DialogResult = DialogResult.OK;
                //ryProcessManager.Config.clsPram.isCloseConfirm = false;
                //ryProcessManager.Config.clsPram.appForm.notifyTray.Visible = false;
                //ryProcessManager.Config.clsPram.appForm.Close();
            }
            else
            {
                RunFile(Application.StartupPath + "\\Update\\" + m_myLiveUpdate.SaveFileName, "");
                this.Close();
            }
        }

        private void FrmStartUpdate_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            Timer1.Enabled = false;
            BtnOK.PerformClick();
        }
        bool haveupdate_zip = false;
        string downname = "";
        bool isRunning = false;
        bool last_mainRunning = false;
        private void FrmStartUpdate_Shown(object sender, EventArgs e)
        {
            m_myLiveUpdate.ProgressChanged += LiveUpdateProgressChanged;
            isRunning = true;
            if (m_myLiveUpdate.UpdateType.FirstDownList != "")
            {
                Thread th = new Thread(DownList)
                {
                    IsBackground = true
                };
                th.Start();
                void DownList()
                {
                    string[] downlist = m_myLiveUpdate.UpdateType.FirstDownList.Replace("\r", "").Split('\n');
                    for (int i = 0; i < downlist.Length; i++)
                    {
                        string[] item = downlist[i].Split('|');
                        if (item.Length < 4) { continue; }
                        if (isExit) { break; }
                        string file_id = item[0]; string file_ver = item[1];string file_size=item[2] ; string file_url = item[3]; string file_path = item[4];
                        bool have_update = false;
                        ryCommon.Storage myStor = new ryCommon.Storage();
                        myStor.LoadFromFile(Application.StartupPath + "\\SysDb\\ver.dat");
                        if (myStor.SelectNode2("id", file_id) == 1 && System.IO.File.Exists(Application.StartupPath + "\\"+ file_path))
                        {
                            if (myStor.GetAttrValue("file_ver","") != file_ver) { have_update = true; }
                            else
                            {
                               if(ryCommon.RyFiles.GetFileSize(Application.StartupPath + "\\" + file_path).ToString()!= file_size)
                               {
                                    have_update = true;
                                }
                            }
                        }
                        else
                        {
                            have_update = true;
                        }
                        if (have_update)
                        {
                            downname = file_id+"["+(i+1).ToString()+ "/"+ downlist.Length+"]";
                            this.Invoke(new Action(() =>
                            {
                                label1.Text = "正在下载" + downname + ",请稍后.."; 
                            }));             
                            if (m_myLiveUpdate.DownloadInUI(file_url, Application.StartupPath + "\\Update\\" + System.IO.Path.GetFileName(file_path)))
                            {
                                string errormsg = "";
                                ryCommon.RyFiles.CopyFile(Application.StartupPath + "\\Update\\" + System.IO.Path.GetFileName(file_path), Application.StartupPath + "\\" + file_path, false, false, false, ref errormsg);
                                myStor.SelectNode2("id", file_id);
                                myStor.SetAttrValue("file_ver", file_ver);
                                myStor.SetAttrValue("file_path", file_path);
                                myStor.SaveToFile(Application.StartupPath + "\\SysDb\\ver.dat");
                            }
                        }
                    }
                    haveupdate_zip = true;
                    this.Invoke(new Action(() =>
                    {
                        label1.Text = "软件正在下载升级文件,请稍后。。。。"; 
                    }));
                    if (!isExit)
                    {
                        last_mainRunning = true;
                        m_myLiveUpdate.StartDownload();
                    }
                    else { isRunning = false; }
                }
            }
            else
            {
                last_mainRunning = true;
                haveupdate_zip = true;
                m_myLiveUpdate.StartDownload();
            }
        }
        bool isExit = false;
        private void frmStartUpdate_FormClosing(object sender, FormClosingEventArgs e)
        {
            isExit = true;
            m_myLiveUpdate.isExit = true;
            if (isRunning)
            {
                e.Cancel = true;
                Thread th = new Thread(WaitClose)
                {
                    IsBackground = true
                };
                th.Start() ;
                return;
            }
            void WaitClose()
            {
                Thread.Sleep(1000);
                this.BeginInvoke(new Action(() =>
                {
                    Close(); 
                }));
            }
        }
    }
}
