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;
using System.IO;
using System.IO.Compression;
using AR;

namespace Project.Dialog
{
    public partial class fUpdateForm : Form
    {
        private Boolean fMove = false;
        private Point MDownPos;
        private string _drive = string.Empty;

        public fUpdateForm()
        {
            InitializeComponent();
        }

        public fUpdateForm(string drvName)
        {
            InitializeComponent();
            _drive = drvName;
            this.FormClosing += fMsgWindow_FormClosing;
            this.KeyDown += FJobSelect_KeyDown;
            this.lbTitle.MouseMove += label1_MouseMove;
            lbTitle.MouseUp += label1_MouseUp;
            lbTitle.MouseDown += label1_MouseDown;
            lbTitle.MouseDoubleClick += label1_MouseDoubleClick;

            
        }

        void fMsgWindow_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void fMsg_Load(object sender, EventArgs e)
        {
            //해당드라이브에서 패치를 체크한다.
            // AGV폴더 아래에 Patch_AGV_20200407.zip 식으로 파일을 처리한다

            lb3.ProgressValue = 0;
            lb3.Text = "--";
            lb1.Text = string.Format("드라이브 : {0}", _drive);
            lb2.Text = "현재버젼 : " + PUB.PatchVersion;
            var dir = System.IO.Path.Combine(this._drive, "AGV");
            if(System.IO.Directory.Exists(dir))
            {
                //폴더는 있다
                var files = System.IO.Directory.GetFiles(dir, "Patch_AGV_*.zip");
                if(files == null || files.Length == 0)
                {
                    arLabel1.Text = "패치파일이 없습니다";
                }
                else
                {
                    var LastFile = files.OrderByDescending(t => t).FirstOrDefault();
                    var splbuf = LastFile.Split('_');

                    patchversion = splbuf[2] + splbuf[3].ToUpper().Replace(".ZIP", "");
                    arLabel1.Text = "패치버젼 : " + patchversion;
                    arLabel1.Tag = LastFile;
                    btYes.Enabled = true;
                }
            }
            else
            {
                arLabel1.Text = "패치폴더("+dir +")가 없습니다";
              
            }
        }
        string patchversion = "";
        private void FJobSelect_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                e.Handled = true;
                e.SuppressKeyPress = false;
                DialogResult = DialogResult.Cancel;
                this.Close();
            }                
            else if (e.KeyCode == Keys.F5)
                btYes.PerformClick();
        }

        //public void setMessage(string msg)
        //{
        //    //msg를 분리해서 표시를 한다.
        //    var lbs = new arCtl.arLabel[] { lbTitle, lb1, lb2, lb3 };
        //    var lineBuf = msg.Replace("\r", "").Split('\n');
        //    int maxLine = Math.Min(lbs.Length, lineBuf.Length);

        //    for (int i = 0; i < lbs.Length; i++)   //최대줄을 넘어가는건 표시불가
        //    {
        //        if (i >= lineBuf.Length)
        //        {
        //            lbs[i].Text = string.Empty;
        //        }
        //        else
        //        {
        //            if (i > 0) lbs[i].Text = string.Format("{0}. {1}", i, lineBuf[i]);
        //            else lbs[i].Text = lineBuf[i];
        //        }

        //    }
        //}



        private void label1_MouseMove(object sender, MouseEventArgs e)
        {
            if (fMove)
            {
                Point offset = new Point(e.X - MDownPos.X, e.Y - MDownPos.Y);
                this.Left += offset.X;
                this.Top += offset.Y;
                offset = new Point(0, 0);
            }
        }

        private void label1_MouseUp(object sender, MouseEventArgs e)
        {
            fMove = false;
        }

        private void label1_MouseDown(object sender, MouseEventArgs e)
        {
            MDownPos = new Point(e.X, e.Y);
            fMove = true;
        }

        private void label1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
          

        }
        public enum EWinColor
        {
            Attention = 0,
            Error,
            Information
        }

        public void SetWindowColor(EWinColor wincolor)
        {
            switch (wincolor)
            {
                case EWinColor.Attention:
                    lbTitle.BackColor = Color.Gold;
                    lbTitle.BackColor2 = Color.Orange;
                    lbTitle.ShadowColor = Color.FromArgb(150, 150, 150);
                    lbTitle.ForeColor = Color.FromArgb(50, 50, 50);
                    break;
                case EWinColor.Error:
                    lbTitle.BackColor = Color.Brown;
                    lbTitle.BackColor2 = Color.Tomato;
                    lbTitle.ShadowColor = Color.FromArgb(50, 50, 50);
                    lbTitle.ForeColor = Color.WhiteSmoke;
                    break;
                default:
                    lbTitle.BackColor = Color.DarkTurquoise;
                    lbTitle.BackColor2 = Color.LightSkyBlue;
                    lbTitle.ShadowColor = Color.FromArgb(50, 50, 50);
                    lbTitle.ForeColor = Color.WhiteSmoke;
                    break;
            }
        }

        private void lbTitle_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void tmBlink_Tick(object sender, EventArgs e)
        {
            var bg1 = lbTitle.BackColor;
            var bg2 = lbTitle.BackColor2;
            lbTitle.BackColor = (Color)bg2;
            lbTitle.BackColor2 = (Color)bg1;
        }

        private void btYes_Click(object sender, EventArgs e)
        {
            //파일
            var file = arLabel1.Tag.ToString();
            if(System.IO.File.Exists(file))
            {
                //이 파일을 _patch 폴더에 압축해제한다.
                var dir_path = new System.IO.DirectoryInfo(System.IO.Path.Combine(UTIL.CurrentPath ,"_patch"));
                if (dir_path.Exists == true)
                {
                    try
                    {
                        dir_path.Delete(true);
                    } catch (Exception ex)
                    {
                        UTIL.MsgE(ex.Message);
                        return;
                    }
                }
                else
                {
                    dir_path.Create(); //폴더를 생성해준다.
                }

                //해당폴더에 압축을 해제해준다.
                ZipFile.ExtractToDirectory(file, dir_path.FullName);

                //패치정보파일 추가
                var infofile = System.IO.Path.Combine(dir_path.FullName, "version.txt");
                System.IO.File.WriteAllText(infofile, patchversion, System.Text.Encoding.UTF8);

                DialogResult = DialogResult.Yes;
                this.Close();
            }
            else
            {
                UTIL.MsgE("패치파일이 없습니다\n" + file);
                return;
            }
            
        }

        private void F_ExtractProgress(object sender, EventArgs e)
        {
            // System.IO.Compression은 진행률 이벤트를 제공하지 않으므로
            // 필요한 경우 별도의 진행률 계산 로직을 구현해야 합니다.
        }

        private void btNo_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel; 
             this.Close();

        }
    }
}
