/*
 * 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;
	using LibSernatur.Misc;

	/**
	 * The tourist editor window class
	 */
	[GtkTemplate (ui = "/cl/cromer/ubb/sernatur/tourist.editor.ui")]
	public class TouristEditor : Gtk.ApplicationWindow {
		/**
		 * The open database connection
		 */
		private Connection conn;
		/**
		 * The tourist to edit
		 */
		private Turista tourist;
		/**
		 * The tourist run
		 */
		[GtkChild]
		private Gtk.Entry run;
		/**
		 * The tourist name
		 */
		[GtkChild]
		private Gtk.Entry tourist_name;
		/**
		 * The birth year
		 */
		[GtkChild]
		private Gtk.SpinButton year;
		/**
		 * The birth day
		 */
		[GtkChild]
		private Gtk.SpinButton day;
		/**
		 * The birth month
		 */
		[GtkChild]
		private Gtk.ComboBoxText month;
		/**
		 * The save button
		 */
		[GtkChild]
		private Gtk.Button save;
		/**
		 * The illnesses button
		 */
		[GtkChild]
		private Gtk.Button illnesses;
		/**
		 * The cancel button
		 */
		[GtkChild]
		private Gtk.Button cancel;
		/**
		 * A list of associated places, this is only used in the case of a new tourist
		 */
		//private List<Asociado> list_asociado = null;
		/**
		 * A saved copy of the original RUN
		 */
		private string original_run;
		/**
		 * This signal is called when a tourist is saved
		 */
		public signal void save_tourist ();

		/**
		 * Validate the tourist data before trying to insert it into the database
		 * @return Returns true if the data is valid
		 */
		private bool validate_tourist_data () {
			if (tourist.nombre_turista.strip () == "") {
				var msg = new Gtk.MessageDialog (this,
					Gtk.DialogFlags.MODAL,
					Gtk.MessageType.ERROR,
					Gtk.ButtonsType.CLOSE,
					_ ("Error: Tourist name cannot be left blank!"));
				msg.response.connect ((response_id) => {
					msg.destroy ();
				});
				msg.set_title (_ ("Error"));
				msg.run ();
				return false;
			}
			if (tourist.rut_turista.strip () == "") {
				var msg = new Gtk.MessageDialog (this,
					Gtk.DialogFlags.MODAL,
					Gtk.MessageType.ERROR,
					Gtk.ButtonsType.CLOSE,
					_ ("Error: Tourist RUN cannot be left blank!"));
				msg.response.connect ((response_id) => {
					msg.destroy ();
				});
				msg.set_title (_ ("Error"));
				msg.run ();
				return false;
			}
			try {
				new Rut (tourist.rut_turista.strip ());
			}
			catch (Error e) {
				var msg = new Gtk.MessageDialog (this,
					Gtk.DialogFlags.MODAL,
					Gtk.MessageType.ERROR,
					Gtk.ButtonsType.CLOSE,
					_ ("Error: The RUN entered is invalid!"));
				msg.response.connect ((response_id) => {
					msg.destroy ();
				});
				msg.set_title (_ ("Error"));
				msg.run ();
				return false;
			}
			if (tourist_exists () && tourist.rut_turista != original_run) {
				var msg = new Gtk.MessageDialog (this,
					Gtk.DialogFlags.MODAL,
					Gtk.MessageType.ERROR,
					Gtk.ButtonsType.CLOSE,
					_ ("Error: A tourist with the RUN \"%s\" already exists!"), tourist.rut_turista);
				msg.response.connect ((response_id) => {
					msg.destroy ();
				});
				msg.set_title (_ ("Error"));
				msg.run ();
				return false;
			}
			return true;
		}

		private bool tourist_exists () {
			try {
				tourist.rut_turista = new Rut (run.get_text ().strip ()).get_clean_rut ();
			}
			catch (Error e) {
				#if DEBUG
					error (e.message);
				#else
					warning (e.message);
				#endif
			}
			try {
				Turista turista = Turista.get_turista_by_run (conn, tourist.rut_turista);
				if (turista == null) {
					return false;
				}
				else {
					return true;
				}
			}
			catch (Error e) {
				#if DEBUG
					error (e.message);
				#else
					warning (e.message);
					return false;
				#endif
			}
		}

		/**
		 * This callback is called when a button is clicked
		 * @param button The button that was clicked
		 */
		[GtkCallback]
		public void on_clicked_button (Gtk.Button button) {
			if (button == save) {
				if (update_tourist_instance () && validate_tourist_data ()) {
					if (!tourist_exists () && original_run == null) {
						try {
							Turista.insert_tourist (conn, tourist);
							/*if (list_asociado != null) {
								// Not enough time
								// Insert all the pending illnesses
								list_asociado.foreach ((entry) => {
									try {
										//Asociado.insert_asociado (conn, entry);
									}
									catch (Error e) {
										#if DEBUG
											error (e.message);
										#else
											warning (e.message);
										#endif
									}
								});
							}*/
							save_tourist (); // Signal the parent to update itself
							this.close ();
						}
						catch (Error e) {
							#if DEBUG
								error (e.message);
							#else
								warning (e.message);
							#endif
						}
					}
					else {
						try {
							Turista.update_tourist (conn, tourist, original_run);
						}
						catch (Error e) {
							#if DEBUG
								error (e.message);
							#else
								warning (e.message);
							#endif
						}
						finally {
							save_tourist (); // Signal the parent to update itself
							this.close ();
						}
					}
				}
			}
			else if (button == illnesses) {
				var tourist_illnesses = new TouristIllnesses (application, conn, tourist);
				tourist_illnesses.set_transient_for (this); // Set this window as the parent of the new window
				tourist_illnesses.initialize ();
				tourist_illnesses.show_all ();
				//tourist_illnesses.save_places.connect (on_save_places);
			}
			else if (button == cancel) {
				this.close ();
			}
		}

		/**
		 * Called when some associated places are saved and a tourist id doesn't exist yet
		 * @param tourist_places The TouristPlaces instance that called this signal
		 * @param list_asociado The list of new associations
		 */
		/*private void on_save_places (TouristPlaces tourist_places, List<Asociado> list_asociado) {
			this.list_asociado = list_asociado.copy ();
			places.sensitive = false;
		}*/

		/**
		 * Called when a vehcile is assigned to the tourist, and the tourist is not in the database yet
		 * @param tourist_assign_vehicle The TouristAssignVehicle instance that called this signal
		 * @param requerir_auto The vehicle to assign to this tourist
		 */
		/*private void on_save_vehicle (TouristAssignVehicle tourist_assign_vehicle, RequerirAuto? requerir_auto) {
			if (requerir_auto != null) {
				this.requerir_auto = requerir_auto;
				vehicle.sensitive = false;
			}
		}*/

		/**
		 * Update the the tourist object with new info from the editor
		 * @return Returns false if the information is not valid
		 */
		private bool update_tourist_instance () {
			tourist.rut_turista = run.get_text ().strip ();
			tourist.nombre_turista = tourist_name.get_text ().strip ();
			tourist.fecha_nacimento = year.get_value ().to_string () + "-" +
				(month.get_active () + 1).to_string () + "-" +
				day.get_value ().to_string ();
			return true;
		}

		/**
		 * Initialize the tourist editor class
		 * @param application The application used to make the GLib object
		 * @param conn The database connection to use
		 * @param tourist The tourist to edit
		 */
		public TouristEditor (Gtk.Application application, Connection conn, Turista? tourist) {
			Object (application: application);
			this.conn = conn;
			this.tourist = tourist;
		}

		/**
		 * Initialize what is needed for this window
		 */
		public void initialize () {
			if (tourist != null) {
				original_run = tourist.rut_turista;
				try {
					run.set_text (new Rut (tourist.rut_turista).get_rut ());
				}
				catch (Error e) {
					#if DEBUG
						error (e.message);
					#else
						warning (e.message);
					#endif
				}
				tourist_name.set_text (tourist.nombre_turista);

				string[] birth_date = tourist.fecha_nacimento.split ("-", 3);
				year.set_value (double.parse (birth_date[0]));
				month.set_active (int.parse (birth_date[1]) - 1);
				day.set_value (double.parse (birth_date[2]));
			}
			else {
				illnesses.destroy ();
				tourist = new Turista ();
			}
		}
	}
}
