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

namespace Patch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "Software Patch";
            this.Show();
           
            Application.DoEvents();

            //현재폴더에서 _patch 폴더 찾는다
            Boolean runClient = true;
            var srcpath = new System.IO.DirectoryInfo ( System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "_patch"));
            if (srcpath.Exists == true)
            {
                //기존 프로그램 종료될떄까지 기다린다
                this.Text = "기존 프로그램 종료 대기";
                Application.DoEvents();
                bool closeok = true;
                System.Diagnostics.Stopwatch wat = new System.Diagnostics.Stopwatch();
                wat.Restart();
                while (CheckExistProcess("Amkor") == true)
                {
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(10);
                    if(wat.ElapsedMilliseconds >= 10000)
                    {
                        MessageBox.Show("기존프로그램이 종료되지 않았습니다", "패치실패", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        closeok = false;
                        break;
                    }
                }

                if (CheckExistProcess("Amkor") == false)
                {

                    //버젼체크하고 파일 복사해준다
                    var files = srcpath.GetFiles();
                    this.progressBar1.Maximum = files.Length;
                    this.progressBar1.Value = 0;
                    this.progressBar1.Style = ProgressBarStyle.Continuous;

                    var myPath = new System.IO.DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

                    try
                    {
                        foreach (var file in files)
                        {
                            this.Text = "패치파일 : " + file.Name;
                            Application.DoEvents();

                            file.CopyTo(System.IO.Path.Combine(file.Directory.Parent.FullName, file.Name), true); // System.IO.File.Copy(file, myPath.FullName, true);
                            this.progressBar1.Value += 1;
                            System.Threading.Thread.Sleep(100);
                        }

                        //패치파일을 삭제한다
                        srcpath.Delete(true);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else runClient = false;
            }

            //클라이언트실행
            if(runClient==true)
            {
                var file_run = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Amkor.exe");
                RunProcess(file_run);
            }
            
            //프로그래램 종료
            this.Close();
        }

        public  Boolean CheckExistProcess(string ProcessName)
        {
            foreach (var prc in System.Diagnostics.Process.GetProcesses())
            {
                if (prc.ProcessName.StartsWith("svchost")) continue;
                if (prc.ProcessName.ToUpper() == ProcessName.ToUpper()) return true;
            }
            return false;
        }

        public Boolean RunProcess(string file, string arg = "")
        {
            var fi = new System.IO.FileInfo(file);
            if (!fi.Exists)
            {
                //Pub.log.AddE("Run Error : " + file);
                return false;
            }
            System.Diagnostics.Process prc = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo(file);
            si.Arguments = arg;
            prc.StartInfo = si;
            prc.Start();
            return true;
        }

    }
}
