/*
 * Copyright 2018-2019 Chris Cromer
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

namespace Sernatur {
	using LibSernatur.DB;

	/**
	 * The MainWindow class
	 */
	[GtkTemplate (ui = "/cl/cromer/ubb/sernatur/main.window.ui")]
	public class MainWindow : Gtk.ApplicationWindow {
		/**
		 * The opened database connection
		 */
		private Connection conn;
		/**
		 * The content grid to fill
		 */
		private Gtk.Grid content;
		/**
		 * The mainbox of the window
		 */
		[GtkChild]
		private Gtk.Box mainbox;
		/**
		 * The tours menu item
		 */
		[GtkChild]
		private Gtk.MenuItem tours;
		/**
		 * The Q1 menu item
		 */
		[GtkChild]
		private Gtk.MenuItem q1;
		/**
		 * The Q2 menu item
		 */
		[GtkChild]
		private Gtk.MenuItem q2;
		/**
		 * The Q3 menu item
		 */
		[GtkChild]
		private Gtk.MenuItem q3;
		/**
		 * The Q4 menu item
		 */
		[GtkChild]
		private Gtk.MenuItem q4;
		/**
		 * The Q5 menu item
		 */
		[GtkChild]
		private Gtk.MenuItem q5;
		/**
		 * The quit menu item
		 */
		[GtkChild]
		private Gtk.MenuItem quit;

		/**
		 * This is a callback for when the close button is pressed on the window
		 * @param widget The widget that called this GtkCallback
		 */
		[GtkCallback]
		private void on_destroy(Gtk.Widget widget) {
			application.quit ();
		}

		/**
		 * This is a callback for when the window is maximized or unmaximized
		 * @param widget The widget that called this GtkCallback
		 * @param state The event window state_handler
		 * @return Returns true if the event is handled or false if it isn't
		 */
		[GtkCallback]
		private bool on_window_state_event(Gtk.Widget widget, Gdk.EventWindowState state) {
			var settings = new Settings ("cl.cromer.ubb.sernatur.window");
			if (state.changed_mask == Gdk.WindowState.MAXIMIZED && (state.new_window_state & Gdk.WindowState.MAXIMIZED) != 0) {
				// Maximized
				settings.set_boolean ("maximized", true);
			}
			else if (state.changed_mask == Gdk.WindowState.MAXIMIZED && (state.new_window_state & Gdk.WindowState.MAXIMIZED) == 0) {
				// Unmaximized
				settings.set_boolean ("maximized", false);
			}
			return false;
		}

		/**
		 * This is a callback for when the window's size is changed
		 * @param widget The widget that called this GtkCallback
		 * @param event The event that happened
		 * @return Returns true if the event is handled or false if it isn't
		 */
		[GtkCallback]
		private bool on_configure_event(Gtk.Widget widget, Gdk.Event event) {
			var settings = new Settings ("cl.cromer.ubb.sernatur.window");
			if (event.get_event_type () == Gdk.EventType.CONFIGURE && !settings.get_boolean ("maximized")) {
				if (settings.get_int ("width") != event.get_window ().get_width ()) {
					settings.set_int ("width", event.get_window ().get_width ());
				}
				if (settings.get_int ("height") != event.get_window ().get_height ()) {
					settings.set_int ("height", event.get_window ().get_height ());
				}
			}
			return false;
		}

		/**
		 * This is a callback for when a menu item is clicked
		 * @param menu_item The menu item that was clicked
		 */
		[GtkCallback]
		private void on_activate_menu(Gtk.MenuItem menu_item) {
			if (menu_item == tours) {
				var tour_list = new TourList (application, conn);
				tour_list.set_transient_for (this); // Set this window as the parent of the new window
				tour_list.initialize ();
				tour_list.show_all ();
			}
			else if (menu_item == q1) {
				var query_window = new QueryWindow (application, conn, Query.Q1);
				query_window.set_transient_for (this); // Set this window as the parent of the new window
				query_window.initialize ();
				query_window.show_all ();
			}
			else if (menu_item == q2) {
				var query_window = new QueryWindow (application, conn, Query.Q2);
				query_window.set_transient_for (this); // Set this window as the parent of the new window
				query_window.initialize ();
				query_window.show_all ();
			}
			else if (menu_item == q3) {
				var query_window = new QueryWindow (application, conn, Query.Q3);
				query_window.set_transient_for (this); // Set this window as the parent of the new window
				query_window.initialize ();
				query_window.show_all ();
			}
			else if (menu_item == q4) {
				var query_window = new QueryWindow (application, conn, Query.Q4);
				query_window.set_transient_for (this); // Set this window as the parent of the new window
				query_window.initialize ();
				query_window.show_all ();
			}
			else if (menu_item == q5) {
				var query_window = new QueryWindow (application, conn, Query.Q5);
				query_window.set_transient_for (this); // Set this window as the parent of the new window
				query_window.initialize ();
				query_window.show_all ();
			}
			else if (menu_item == quit) {
				application.quit ();
			}
		}

		/**
		* Initialize the main window class
		* @param application The application used to make the GLib object
		*/
		public MainWindow (Gtk.Application application) {
			GLib.Object (application: application);

			// Load logo
			var builder = new Gtk.Builder ();
			try {
				builder.add_from_resource ("/cl/cromer/ubb/sernatur/main.splash.ui");
				builder.connect_signals (null);
				content = builder.get_object ("content_grid") as Gtk.Grid;

				// Add logo to main box
				mainbox.pack_start (content, true, false, 0);
			}
			catch (Error e) {
				// This error is not fatal, so let's keep going
				warning (e.message);
			}
		}

		/**
		 * Initialize what is needed for this window
		 */
		public void initialize () {
			var settings = new Settings ("cl.cromer.ubb.sernatur.db");
			var host = settings.get_string ("host");
			var port = settings.get_string ("port");
			var options = settings.get_string ("options");
			var tty = settings.get_string ("tty");
			var database = settings.get_string ("database");
			var username = settings.get_string ("username");
			var password = settings.get_string ("password");

			try {
				conn = new Connection (host, port, options, tty, database, username, password);
			}
			catch (Error e) {
				#if DEBUG
					error (e.message);
				#else
					warning (e.message);
					var msg = new Gtk.MessageDialog (this,
						Gtk.DialogFlags.MODAL,
						Gtk.MessageType.ERROR,
						Gtk.ButtonsType.CLOSE,
						dgettext(null, "Error: Could not connect to the database!"));
					msg.response.connect ((response_id) => {
						switch (response_id) {
							case Gtk.ResponseType.CLOSE:
								application.quit ();
								break;
							case Gtk.ResponseType.DELETE_EVENT:
								application.quit ();
								break;
						}
						msg.destroy ();
					});
					msg.set_title (dgettext (null, "Error"));
					msg.show ();
					return;
				#endif
			}
		}
	}
}
