using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoneUpdater.Class;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Runtime.InteropServices;

namespace StoneUpdater
{
    public partial class FrmUpdater : Form
    {
        public FrmUpdater()
        {
            InitializeComponent();
        }

        private const int SC_CLOSE = 0xF060;
        private const int MF_GRAYED = 0x1;
        [DllImport("user32.dll")]
        private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
        [DllImport("user32.dll")]
        private static extern int EnableMenuItem(IntPtr hMenu, int wIDEnableItem, int wEnable);


        private void Form1_Load(object sender, EventArgs e)
        {
            

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {

            if (lblpath.Text == "...")
            {
                   MessageBox.Show("لطفا فایل فشرده ، بروزرسانی را انتخاب کنید ", "زمرد", MessageBoxButtons.OK, MessageBoxIcon.Information);
                   return;
            }

            EnableMenuItem(GetSystemMenu(this.Handle, false), SC_CLOSE, MF_GRAYED);

            try
            {

                #region Extract Files Update
                try
                {

                    progressBar1.Style = ProgressBarStyle.Marquee;

                    if (!Directory.Exists(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater"))
                    {
                        Directory.CreateDirectory(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater");
                    }
                    ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry;
                    ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(lblpath.Text);

                    zipFile.Password = "Pars775";

                    lblOperation.Text = " استخراج فایلها ";

                    for (int n = 0; n < zipFile.Size; n++)
                    {
                        zipEntry = zipFile[n];

                        if (zipEntry != null)
                        {
                            Stream inputStream = zipFile.GetInputStream(zipEntry);
                            FileStream fileStream = new FileStream(
                                Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\", zipEntry.Name),
                                FileMode.Create);
                            CopyStream(inputStream, fileStream);
                            fileStream.Close();
                            inputStream.Close();
                        }
                    }

                    progressBar1.Style = ProgressBarStyle.Blocks;
                }
                catch (Exception ex)
                {
                    if (ex.Message == "Invalid password")
                    {
                        MessageBox.Show("رمز فایل اشتباه است ", "زمرد", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        progressBar1.Style = ProgressBarStyle.Blocks;
                        lblOperation.Text = "...";
                    }
                }

                #endregion.


                #region Operation
                Updater updateSoft = new Updater();
                lblOperation.Text = "  بروزرسانی برنامه ";
                progressBar1.Style = ProgressBarStyle.Marquee;
                for (int i = 0; i <= updateSoft.Update.Rows.Count - 1; i++)
                {

                    #region CopyFiles

                    if (updateSoft.Update.Rows[i]["Operation"].ToString() == "CopyFile")
                    {



                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "AppFolder")
                        {
                            File.Copy(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\"
                                      + updateSoft.Update.Rows[i]["Name"].ToString(), Application.StartupPath +"\\"
                                      + updateSoft.Update.Rows[i]["Name"].ToString(), true);
                        }



                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "ApplicationData")
                        {
                            File.Copy(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\"
                                      + updateSoft.Update.Rows[i]["Name"].ToString(), System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB\\"
                                      + updateSoft.Update.Rows[i]["Name"].ToString(), true);
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Font")
                        {
                            File.Copy(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\"
                                     + updateSoft.Update.Rows[i]["Name"].ToString(), System.Environment.GetFolderPath(System.Environment.SpecialFolder.Fonts) + "\\"
                                     + updateSoft.Update.Rows[i]["Name"].ToString(), true);
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Windows")
                        {
                            File.Copy(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\"
                                + updateSoft.Update.Rows[i]["Name"].ToString(), System.Environment.GetFolderPath(System.Environment.SpecialFolder.Windows) + "\\"
                                + updateSoft.Update.Rows[i]["Name"].ToString(), true);
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "MyDocuments")
                        {
                            if (!Directory.Exists(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB"))
                            {
                                Directory.CreateDirectory(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB");
                            }
                            File.Copy(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\"
                               + updateSoft.Update.Rows[i]["Name"].ToString(), System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB\\"
                               + updateSoft.Update.Rows[i]["Name"].ToString(), true);
                        }

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Other")
                        {
                            File.Copy(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\"
                               + updateSoft.Update.Rows[i]["Name"].ToString(),
                               updateSoft.Update.Rows[i]["Target1"].ToString(), true);
                        }





                    }

                    #endregion


                    #region DelFiles
                    if (updateSoft.Update.Rows[i]["Operation"].ToString() == "DelFile")
                    {

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "AppFolder")
                        {

                            File.Delete(Application.StartupPath + "\\" +
                                     updateSoft.Update.Rows[i]["Name"].ToString());

                        }



                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "ApplicationData")
                        {
                            File.Delete(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB\\" +
                                       updateSoft.Update.Rows[i]["Name"].ToString());
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Font")
                        {
                            File.Delete(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Fonts) + "\\" +
                                       updateSoft.Update.Rows[i]["Name"].ToString());
                        }

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Windows")
                        {
                            File.Delete(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Windows) + "\\" +
                                         updateSoft.Update.Rows[i]["Name"].ToString());
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "MyDocuments")
                        {
                            File.Delete(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB\\" +
                                       updateSoft.Update.Rows[i]["Name"].ToString());
                        }

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Other")
                        {
                            File.Delete(updateSoft.Update.Rows[i]["Target1"].ToString());
                        }




                    }
                    #endregion


                    #region MoveFiles
                    if (updateSoft.Update.Rows[i]["Operation"].ToString() == "MoveFile")
                    {



                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "AppFolder")
                        {
                            File.Move(Application.StartupPath + "\\"
                                      + updateSoft.Update.Rows[i]["Name"].ToString(),
                                       System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\" + updateSoft.Update.Rows[i]["Name"].ToString());
                        }

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "ApplicationData")
                        {
                            File.Move(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB\\"
                                      + updateSoft.Update.Rows[i]["Name"].ToString(),
                                       System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\" + updateSoft.Update.Rows[i]["Name"].ToString());
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Font")
                        {
                            File.Move(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Fonts) + "\\"
                                       + updateSoft.Update.Rows[i]["Name"].ToString(),
                                         System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\" + updateSoft.Update.Rows[i]["Name"].ToString());
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Windows")
                        {
                            File.Move(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Windows) + "\\"
                                      + updateSoft.Update.Rows[i]["Name"].ToString(),
                                        System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\" + updateSoft.Update.Rows[i]["Name"].ToString());
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "MyDocuments")
                        {
                            File.Move(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB\\"
                                      + updateSoft.Update.Rows[i]["Name"].ToString(),
                                        System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\" + updateSoft.Update.Rows[i]["Name"].ToString());
                        }

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Other")
                        {
                            File.Move(updateSoft.Update.Rows[i]["Target1"].ToString(), System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater\\" + updateSoft.Update.Rows[i]["Name"].ToString());
                        }

                    }

                    #endregion


                    #region AddReg
                    if (updateSoft.Update.Rows[i]["Operation"].ToString() == "AddReg")
                    {
                        updateSoft.Create_key_Registery(updateSoft.Update.Rows[i]["Target1"].ToString()
                            , updateSoft.Update.Rows[i]["Name"].ToString()
                            , updateSoft.Update.Rows[i]["Value"].ToString());

                    }
                    #endregion


                    #region DelReg
                    if (updateSoft.Update.Rows[i]["Operation"].ToString() == "DelReg")
                    {
                        updateSoft.Delete_key_Registery(updateSoft.Update.Rows[i]["Target1"].ToString()
                           , updateSoft.Update.Rows[i]["Name"].ToString()
                           , updateSoft.Update.Rows[i]["Value"].ToString());
                    }
                    #endregion


                    #region CreateShortcut
                    if (updateSoft.Update.Rows[i]["Operation"].ToString() == "CreateShortcut")
                    {

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Desktop")
                        {
                            updateSoft.CreateShortcut("Desktop", updateSoft.Update.Rows[i]["Name"].ToString(), updateSoft.Update.Rows[i]["Target1"].ToString());

                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Programs")
                        {
                            updateSoft.CreateShortcut("StartMenu", updateSoft.Update.Rows[i]["Name"].ToString(), updateSoft.Update.Rows[i]["Target1"].ToString());
                        }
                    }
                    #endregion


                    #region CreateDirectory

                    if (updateSoft.Update.Rows[i]["Operation"].ToString() == "CreateDirectory")
                    {


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "AppFolder")
                        {
                            Directory.CreateDirectory(Application.StartupPath +"\\"+
                                                      updateSoft.Update.Rows[i]["Name"].ToString());

                        }

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "ApplicationData")
                        {
                            Directory.CreateDirectory(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB\\" +
                                                      updateSoft.Update.Rows[i]["Name"].ToString());

                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Application")
                        {
                            Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath + "\\" +
                                                     updateSoft.Update.Rows[i]["Name"].ToString());
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Windows")
                        {
                            Directory.CreateDirectory(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Windows) + "\\" +
                                                      updateSoft.Update.Rows[i]["Name"].ToString());
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "MyDocuments")
                        {
                            if (!Directory.Exists(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB"))
                            {
                                Directory.CreateDirectory(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB");
                            }
                            Directory.CreateDirectory(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB\\" +
                                                       updateSoft.Update.Rows[i]["Name"].ToString());
                        }

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Other")
                        {
                            Directory.CreateDirectory(updateSoft.Update.Rows[i]["Target1"].ToString());
                        }

                    }

                    #endregion


                    #region DeleteDirectory

                    if (updateSoft.Update.Rows[i]["Operation"].ToString() == "DeleteDirectory")
                    {


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "AppFolder")
                        {
                            Directory.Delete(Application.StartupPath + "\\" +
                                                      updateSoft.Update.Rows[i]["Name"].ToString());

                        }

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "ApplicationData")
                        {
                            Directory.Delete(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB\\" +
                                                      updateSoft.Update.Rows[i]["Name"].ToString());

                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Application")
                        {
                            Directory.Delete(System.Windows.Forms.Application.StartupPath + "\\" +
                                                     updateSoft.Update.Rows[i]["Name"].ToString());
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Windows")
                        {
                            Directory.Delete(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Windows) + "\\" +
                                                      updateSoft.Update.Rows[i]["Name"].ToString());
                        }


                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "MyDocuments")
                        {
                            if (!Directory.Exists(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB"))
                            {
                                Directory.CreateDirectory(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB");
                            }
                            Directory.Delete(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\ParsZSDB\\" +
                                                       updateSoft.Update.Rows[i]["Name"].ToString());
                        }

                        if (updateSoft.Update.Rows[i]["Value"].ToString() == "Other")
                        {
                            Directory.Delete(updateSoft.Update.Rows[i]["Target1"].ToString());
                        }

                    }

                    #endregion


                }


                progressBar1.Style = ProgressBarStyle.Blocks;
                #endregion


                #region DeleteTempFiles

                lblOperation.Text = " حدف فایلهای موقت ";
                progressBar1.Style = ProgressBarStyle.Marquee;

                DirectoryInfo source = new DirectoryInfo(System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\ParsZSDB" + "\\Updater");
                updateSoft.DeleteUpdatePackage(source);

                progressBar1.Style = ProgressBarStyle.Blocks;
                    
                #endregion


            }
            catch (Exception ex)
            {
                MessageBox.Show( ex.Message + "مشکلی در بروز رسانی بوجود آمده است ", "زمرد", MessageBoxButtons.OK, MessageBoxIcon.Information);
                btnUpdate.Enabled = false;
                EnableMenuItem(GetSystemMenu(this.Handle, false), SC_CLOSE, 0x0);
                lblOperation.Text = " ... ";
                lblPercent.Text = "0 %";
                progressBar1.Style = ProgressBarStyle.Blocks;
                progressBar1.Value = 0;
                return;
            }


            btnUpdate.Enabled = false;
            EnableMenuItem(GetSystemMenu(this.Handle, false), SC_CLOSE, 0x0);
            lblOperation.Text = " ... ";
            lblPercent.Text = "100%";
            progressBar1.Style = ProgressBarStyle.Blocks;
            progressBar1.Value = 100;
            MessageBox.Show("بروز رسانی با موفقیت انجام شد ", "زمرد", MessageBoxButtons.OK, MessageBoxIcon.Information);
            System.Diagnostics.Process.Start(System.Windows.Forms.Application.StartupPath + "\\" + "Stone.exe");
            Application.Exit();
        }



        private static void CopyStream(Stream source, Stream destination)
        {
            byte[] buffer = new byte[4096];
            int countBytesRead;
            while ((countBytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
            {
                destination.Write(buffer, 0, countBytesRead);
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            string fileName = GetFileName("Zip-Archive (*.zip)|*.zip");
            if (fileName != null)
            {
                lblpath.Text = fileName;
                FileInfo SizeFile = new FileInfo(lblpath.Text);
                lblsizefile.Text = ((SizeFile.Length) / 1024).ToString()+" کیلوبایت ";
                btnUpdate.Enabled = true;
            }

          
        }

        private String GetFileName(String filter)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = filter;
            dlg.RestoreDirectory = true;
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                return dlg.FileName;
            }
            else
            {
                return null;
            }
        }
    }
}
