using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using System.Net;
using System.Diagnostics;

using Baza_Reklam.Classes;
using Baza_Reklam.Classes.Helpers;

namespace Baza_Reklam
{
    public partial class FormBadVer : Form
    {
        readonly string _updaterUrl = ConfigurationHelper.GetSettingByKey("Application.Update.Exe") ?? "http://www.infocity.pl/baza_reklam/update/BazaReklam.Updater.exe";
        readonly string _zipUrl = ConfigurationHelper.GetSettingByKey("Application.Update.Zip") ?? "http://www.infocity.pl/baza_reklam/update/BazaReklam.zip";

        private readonly WebClient webClient;

        public FormBadVer()
        {
            InitializeComponent();

            webClient = new WebClient();
            webClient.DownloadFileCompleted += DownloadFileCompleted;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;

            string updater = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "BazaReklam.Updater.exe";

            if (File.Exists(updater))
                StartUpdater();
            else
                webClient.DownloadFileAsync(new Uri(_updaterUrl), Environment.CurrentDirectory + Path.DirectorySeparatorChar + "BazaReklam.Updater.exe");
        }

        private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                StartUpdater();
            }
            else
            {
                MessageBox.Show("Błąd aktualizacji oprogramowania: " + e.Error.Message, "Aktualizacja oprogramowania", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logger.LogException(e.Error, "[aktualizacja]", DateTime.Now);
                Close();
            }
        }

        private void StartUpdater()
        {
            string updater = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "BazaReklam.Updater.exe";
            try
            {
                Cursor = Cursors.Default;
                button1.Cursor = Cursors.Default;

                ProcessStartInfo processStartInfo = new ProcessStartInfo(updater);
                processStartInfo.Arguments = string.Format(" \"{0}\" {1}", "Baza Reklam", _zipUrl);

                Close();

                Process.Start(processStartInfo);
            }
            catch (Exception exception)
            {
                Logger.LogException(exception.Message, exception + "\n" + updater, "[aktualizacja]", DateTime.Now);
                MessageBox.Show("Błąd aktualizacji oprogramowania: " + exception.Message, "Aktualizacja oprogramowania", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}