/*
 * Copyright 2018 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.
 */

/**
 * The main Sernatur namespace
 */
namespace Sernatur {
	using LibSernatur.Person;
	using LibSernatur.DB;

	/**
	 * The MainWindow class
	 */
	[GtkTemplate (ui = "/cl/cromer/ubb/sernatur/sernatur.window.ui")]
	public class MainWindow : Gtk.ApplicationWindow {
		private Gtk.Grid content;
		[GtkChild]
		private Gtk.Box mainbox;

		/**
		 * 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 maximize_window(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 resize_window(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;
		}

		[GtkCallback]
		private void menu_quit(Gtk.MenuItem menu_item) {
			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/splash.ui");
				builder.connect_signals (null);
				content = builder.get_object ("content_grid") as Gtk.Grid;

				// Add logo to main 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);
			}

			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");

			var conn = Postgres.set_db_login (host, port, options, tty, database, username, password);
			if (conn.get_status () != Postgres.ConnectionStatus.OK) {
				#if DEBUG
					error (conn.get_error_message ());
				#else
					warning (conn.get_error_message ());
					var msg = new Gtk.MessageDialog (this,
						Gtk.DialogFlags.MODAL,
						Gtk.MessageType.ERROR,
						Gtk.ButtonsType.CLOSE,
						conn.get_error_message ());
					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
			}
			print (dgettext (null, "Postgresql server version:") + " %d\n", conn.get_server_version ());

			var tour = Tour.get_all_tours (conn);
			print (tour[0].ciudad.region.nombre_region + "\n");
			var tiene_enfermedad = TieneEnfermedad.get_all_tiene_enfermedades (conn);
			print (tiene_enfermedad[0].turista.contacto_emergencia.nombre_emergencia + "\n");
			var descuento = Descuento.get_all_descuentos (conn);
			print (descuento[0].porcentaje.to_string () + "\n");
			var realiza = Realiza.get_all_realizas (conn);
			print (realiza[0].turista.contacto_emergencia.nombre_emergencia + "\n");
			var posee = Posee.get_all_posees (conn);
			print (posee[0].guia.ciudad.region.nombre_region + "\n");
			var region = Region.get_all_regiones (conn);
			print (region[0].nombre_region + "\n");
			var participa = Participa.get_all_participas (conn);
			print (participa[0].guia.ciudad.region.nombre_region + "\n");
			print (participa[0].tour.ciudad.region.nombre_region + "\n");
			var requerir_auto = RequerirAuto.get_all_requerir_autos (conn);
			print (requerir_auto[0].vehiculo.marca + "\n");
			try {
				var rut = new Rut ("23.660.457-8");
				print (rut.get_rut () + "\n");
				if (rut.type () == Rut.Type.RUN) {
					print ("person\n");
				}
				else {
					print ("company\n");
				}
			}
			catch (InvalidRut e) {
				print ("Rut is invalid");
			}
		}
	}
}
