using System;
using System.ComponentModel;
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/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;
            Cursor = Cursors.WaitCursor;
            button1.Cursor = Cursors.WaitCursor;
            webClient.DownloadFileAsync(new Uri(_updaterUrl), Environment.CurrentDirectory + "\\Updater.exe");
            return;

            //TODO: Uncomment after every user will get updated version of the Updater
            //string updater = Environment.CurrentDirectory + "\\Updater.exe";

            //if (System.IO.File.Exists(updater))
            //    StartUpdater();
            //else
            //    webClient.DownloadFileAsync(new Uri(_updaterUrl), Environment.CurrentDirectory + "\\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 + "\\Updater.exe";
            Cursor = Cursors.Default;
            button1.Cursor = Cursors.Default;
            Close();
            Process.Start(updater, string.Format(" \"{0}\" {1}", "Baza Reklam", _zipUrl));
        }
    }
}