/* This file is part of AHD Subtitles Maker Professional
   A program can create and edit subtitles

   Copyright © Ala I Hadid 2009 - 2012

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Reflection;
using AHD.SM.ASMP;
using AHD.Forms;

namespace Updater
{
    public partial class Frm_Main : Form
    {
        string[] args;
        NetUpdate Updates = new NetUpdate();
        Version asmVersion;
        Properties.Settings settings = new Properties.Settings();
        public Frm_Main(string[] args)
        {
            this.args = args;
            InitializeComponent();
            try
            {
                Assembly asm = Assembly.LoadFile(Path.GetFullPath(".\\asm.exe"));
                asmVersion = asm.GetName().Version;
            }
            catch 
            {
                MessageDialog.ShowMessage(Program.ResourceManager.GetString("Message_CantFindASM"),
                      Program.ResourceManager.GetString("Error"), MessageDialogButtons.Ok, MessageDialogIcon.Error);
                richTextBox1.Text = Program.ResourceManager.GetString("Error");
                button1.Enabled = button3.Enabled = false;
            }
        }
        void CheckForUpdates()
        {
            try
            {
                progressBar1.Visible = true;
                string url = "http://files.ahd-subtitles-maker.webnode.com/200000271-5346c538dd/update.xml";

                WebClient webClient = new WebClient();
                if (settings.UseProxy)
                {
                    webClient.Proxy = new WebProxy(settings.ProxyHost, int.Parse(settings.ProxyPort));
                }
                webClient.DownloadFile(url, Path.GetTempPath() + "\\update.xml");
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
                XmlSerializer ser = new XmlSerializer(typeof(NetUpdate));
                FileStream str = new FileStream(Path.GetTempPath() + "\\update.xml", FileMode.Open, FileAccess.Read);
                Updates = (NetUpdate)ser.Deserialize(str);
                str.Close();
                RefreshUpdates();
                progressBar1.Visible = false;
            }
            catch (Exception ex)
            {
                MessageDialog.ShowMessage(Program.ResourceManager.GetString("Message_CantConnectToServer") + "\n\n" + ex.ToString(),
                     Program.ResourceManager.GetString("Error"), MessageDialogButtons.Ok, MessageDialogIcon.Error);
                richTextBox1.Text = Program.ResourceManager.GetString("Message_ConnectionError");
            }
        }
        void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            progressBar1.Refresh();
        }
        void RefreshUpdates()
        {
            listView1.Items.Clear();
            richTextBox1.Text = "";
            foreach (ASMUpdate update in Updates.Updates)
            {
                if (update.IsForASM)
                {
                    Version newVersion = new Version(update.Version);
                    if (newVersion > asmVersion)
                    {
                        ListViewItem item = new ListViewItem();
                        item.Text = update.Name;
                        item.SubItems.Add(update.Version.ToString());
                        item.SubItems.Add(update.FileSize);
                        listView1.Items.Add(item);
                    }
                }
                else
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = update.Name;
                    item.SubItems.Add(update.Version.ToString());
                    item.SubItems.Add(update.FileSize);
                    listView1.Items.Add(item);
                }
            }
            if (listView1.Items.Count == 0)
                richTextBox1.Text = Program.ResourceManager.GetString("Message_TheresNoUpdateAvailableForInstalledVersionOfASM");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem it in listView1.Items)
            {
                if (it.Checked)
                {
                    ASMUpdate update = Updates.Updates[it.Index];
                    try { Process.Start(update.Link); }
                    catch { }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            CheckForUpdates();
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            if (args != null)
            {
                foreach (string arg in args)
                {
                    switch (arg.ToLower())
                    {
                        case "/checknow": CheckForUpdates(); break;
                    }
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Frm_Options opt = new Frm_Options();
            opt.ShowDialog(this);
        }

        private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            button1.Enabled = false;
            foreach (ListViewItem it in listView1.Items)
            {
                if (it.Checked)
                { button1.Enabled = true; break; }
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 1)
            {
                string info = Updates.Updates[listView1.SelectedItems[0].Index].Name+"\n\n";
                info += Updates.Updates[listView1.SelectedItems[0].Index].Description+"\n\nWhat's New ?\n";

                foreach (string feature in Updates.Updates[listView1.SelectedItems[0].Index].Features)
                {
                    info += "* " + feature + "\n";
                }

                richTextBox1.Text = info + "\n" + 
                    Program.ResourceManager.GetString("Message_ItsRecommendedToUninstallCurrentVersionBeforeInstallingThisUpdate");
            }
            else
                richTextBox1.Text = "";
        }
    }
}
