using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Data.SqlClient;

namespace Updater
{
    public partial class UpdateForm : Form
    {

		#region Fields (7) 

        private bool abort = false;
     //   private string connectionString;
        private string zipFileName;
        private string exeFileName;
        private bool isBusy = false;
        private int nMaxProgress = 100;
        private string strUrl;
        private WebClient webClient;

		#endregion Fields 

		#region Constructors (1) 

        public UpdateForm(string rodzajProgramu)
        {
            InitializeComponent();

            switch (rodzajProgramu){
                //BAZA REKLAM
                case "1":
                    strUrl = "http://www.infocity.pl/baza_reklam/Files/BazaReklam.zip";
                    zipFileName = "BazaReklam";
                    exeFileName = "Baza Reklam";
                    this.Text = "Baza reklam - aktualizacja";
                    break;
                //BAZA ZAMOWIEN - BAZA PREMII
                case "2":
                    strUrl = "http://www.infocity.pl/baza_zamowien/Files/BazaZamowien.zip";
                    zipFileName = "BazaZamowien";
                    exeFileName = "BazaZamowien";
                    this.Text = "Baza zamówień | Baza premii - aktualizacja";
                    break;
            }
            
         //   connectionString = connStr;                  
      
            webClient = new WebClient();
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted);
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
        }

		#endregion Constructors 

		#region Methods (9) 


		// Private Methods (9) 

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                Extract(Environment.CurrentDirectory + "\\" + zipFileName + ".zip", Environment.CurrentDirectory);
                MessageBox.Show("Zakończono aktualizację oprogramowania.", "Aktualizacja oprogramowania", MessageBoxButtons.OK, MessageBoxIcon.Information);
                System.Diagnostics.Process.Start(exeFileName + ".exe");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aktualizacja oprogramowania", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            isBusy = false;
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (!this.Visible || this.WindowState != FormWindowState.Normal)
            {
                return;
            }

            if (progressBar1.Maximum != nMaxProgress)
            {
                progressBar1.Maximum = nMaxProgress;
            }

            if (e.ProgressPercentage < progressBar1.Maximum)
            {
                progressBar1.Value = e.ProgressPercentage;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            isBusy = false;
            abort = true;
            webClient.CancelAsync();
            this.Close();
        }

        private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            isBusy = false;
            
            if (abort)
            {
                return;
            }

            if (e.Error == null)
            {
                progressBar1.Value = 0;

                if (File.Exists(exeFileName + ".exe"))
                {
                    File.Delete(exeFileName + ".exe");
                }

               //if (File.Exists(
               // File.Move(exeFileName + ".exe",exeFileName + ".old");

                label1.Text = "Rozpakowywanie archiwum...";              
                backgroundWorker1.RunWorkerAsync();
            }
            else
            {
                MessageBox.Show("Błąd aktualizacji oprogramowania: " + e.Error.Message, "Aktualizacja oprogramowania", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        private void Extract(string zipFileName, string destinationPath)
        {
            
            Shell32.IShellDispatch4 sc = (Shell32.IShellDispatch4) new Shell32.ShellClass();
           
           // Shell32.ShellClass sc = new Shell32.ShellClass();
            Shell32.Folder SrcFlder = sc.NameSpace(zipFileName);
            Shell32.Folder DestFlder = sc.NameSpace(destinationPath);
            Shell32.FolderItems items = SrcFlder.Items();
            nMaxProgress = items.Count;
          //  DestFlder.CopyHere(items, 20);
           
            int n = 0;

            foreach (Shell32.FolderItem item in items)
            {
                DestFlder.CopyHere(item, 20);
                
                ++n;
                if (backgroundWorker1.IsBusy) backgroundWorker1.ReportProgress(n);
            }
            
            
            //Type shellAppType = Type.GetTypeFromProgID("Shell.Application"); 
            //object shell = Activator.CreateInstance(shellAppType);
            //object srcFlder = shell.GetType().InvokeMember(
            //object destFlder = Type.GetTypeFromProgID("Shell.Folder");
             
        }

        private void UpdateForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isBusy || backgroundWorker1.IsBusy)
            {
                e.Cancel = true;
            }
        }

        private void UpdateForm_Shown(object sender, EventArgs e)
        {
            try
            {
                /*
                string connectionString = "Data Source=10.0.0.21;Initial Catalog=DANE_OGL_SQL;Persist Security Info=True;User ID=sa;Password=maro2451;Connection Timeout=600;Application Name=boUpdater";

                SqlConnection conn = new SqlConnection(connectionString);
                conn.Open();

                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT TOP 1 currVer FROM Config";
                string verDb = (string)cmd.ExecuteScalar();
                conn.Close();

                string s1 = Environment.CurrentDirectory;
                s1 += "\\BazaOgl.exe";
                FileVersionInfo boFileVersion = FileVersionInfo.GetVersionInfo(s1);

                if (verDb == boFileVersion.FileVersion)
                {
                    if (MessageBox.Show("Bieżąca wersja pliku (" + verDb + ") jest aktualna.\nCzy napewno chcesz aktualizować program?", "Aktualizacja oprogramowania", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                        return;
                }
                */

                isBusy = true;
                this.progressBar1.Value = 0;
                string s1 = Environment.CurrentDirectory;
                s1 += "\\" + zipFileName + ".zip";

                if (System.IO.File.Exists(s1))
                {
                    System.IO.File.Delete(s1);
                }

                webClient.DownloadFileAsync(new Uri(strUrl), s1);
                label1.Text = "Pobieranie nowej wersji";
            }
            catch (UriFormatException ex)
            {
                MessageBox.Show(ex.Message, "Aktualizacja oprogramowania", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Aktualizacja oprogramowania", MessageBoxButtons.OK, MessageBoxIcon.Error);
                MessageBox.Show(ex.ToString(), "Aktualizacja oprogramowania", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
            }

        }


		#endregion Methods 

    }
}