using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Xml;

namespace OPlanner {

	public partial class UpdateInfo : Window {

		public UpdateInfo() {
			InitializeComponent();
			GetUpdateInfo();
		}

		private void GetUpdateInfo() {
			downloadPanel.Visibility = Visibility.Collapsed;
			XmlDocument doc = new XmlDocument();
			try {
				doc.Load(OPlannerAbout.UpdateCheckUrl);
			} catch (Exception) {
				updateLabel.Content = "Cannot connect to oplanner.org.uk";
				return;
			}
			XmlNode root = doc.SelectSingleNode("UpdateInfo");
			if (root == null) {
				updateLabel.Content = "Cannot read update file";
				return;
			}
			XmlNode node = root.SelectSingleNode("LastUpdated");
			if (node == null) {
				updateLabel.Content = "Cannot read update file";
				return;
			}
			DateTime date;
			if (!DateTime.TryParse(node.InnerText, out date)) {
				updateLabel.Content = "Cannot read update file";
				return;
			}
			if (DateTime.Compare(date, OPlannerAbout.LastUpdated) <= 0) {
				updateLabel.Content = "OPlanner is up to date";
				return;
			}
			updateLabel.Content = "A newer version is available - updated on " + date.ToString("dd-MMM-yyyy HH:mm:ss");
			downloadPanel.Visibility = Visibility.Visible;
		}

		private void okButton_Click(object sender, RoutedEventArgs e) {
			Close();
		}

		private void downloadButton_Click(object sender, RoutedEventArgs e) {
			try {
				Process.Start(OPlannerAbout.DownloadUrl);
			} catch (Exception) {
				ErrorManager errorManager = new ErrorManager();
				errorManager.AddError("Cannot connect to oplanner.org.uk");
				errorManager.ShowErrors(this);
			}
		}

	}

}
