/*
 * 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 tour assign vehicle window class
	 */
	[GtkTemplate (ui = "/cl/cromer/ubb/sernatur/tour.assign.vehicle.ui")]
	public class TourAssignVehicle : Gtk.ApplicationWindow {
		/**
		 * The open database connection
		 */
		private Connection conn;
		/**
		 * The tour to associate with the vehicle
		 */
		private Tour tour;
		/**
		 * The vehicle data stored in the list store
		 */
		private enum Column {
			/**
			 * The details of the vehicle
			 */
			VEHICLE_DETAILS,
			/**
			 * The vehicle object
			 */
			VEHICLE,
			/**
			 * The number of colums in this enum
			 */
			N_COLUMNS
		}
		/**
		 * The chofer of the vehicle
		 */
		[GtkChild]
		private Gtk.Entry chofer;
		/**
		 * The vehicle comboxbox
		 */
		[GtkChild]
		private Gtk.ComboBoxText vehicle;
		/**
		 * The save button
		 */
		[GtkChild]
		private Gtk.Button save;
		/**
		 * The cancel button
		 */
		[GtkChild]
		private Gtk.Button cancel;
		/**
		 * A list of the vehicles from the database
		 */
		private List<Vehiculo> vehicles;
		/**
		 * A vehicle required object from the database
		 */
		private RequerirAuto require_vehicle;
		/**
		 * The list that stores the vehicles for the combo box
		 */
		private Gtk.ListStore vehicle_list_store;
		/**
		 * This signal is called when a vehicle is assigned
		 */
		public signal void save_vehicle (RequerirAuto? requerir_auto);

		/**
		 * Validate the vehicle data before trying to insert it into the database
		 * @return Returns true if the data is valid
		 */
		private bool validate_vehicle_data () {
			if (require_vehicle.chofer.strip () == "") {
				var msg = new Gtk.MessageDialog (this,
					Gtk.DialogFlags.MODAL,
					Gtk.MessageType.ERROR,
					Gtk.ButtonsType.CLOSE,
					_ ("Error: The chofer's name cannot be left blank!"));
				msg.response.connect ((response_id) => {
					msg.destroy ();
				});
				msg.set_title (_ ("Error"));
				msg.run ();
				return false;
			}
			return true;
		}

		/**
		 * Called when a combobox changes
		 * @param combobox The combobox that changed
		 */
		[GtkCallback]
		public void on_changed_combobox (Gtk.ComboBox combobox) {
			if (combobox == vehicle) {
				if (vehicle.get_active () > 0) {
					Gtk.TreeIter iter;
					vehicle.get_active_iter (out iter);
					Vehiculo temp_vehicle;
					vehicle_list_store.get (iter,
						Column.VEHICLE, out temp_vehicle);
					chofer.sensitive = true;
				}
				else {
					chofer.sensitive = false;
				}
			}
		}

		/**
		 * 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_vehicle_instance ()) {
					if (require_vehicle.tour.id_tour != 0) {
						try {
							if (require_vehicle.chofer.strip () == "") {
								RequerirAuto.delete_require_vehicle (conn, tour);
							}
							else {
								if (RequerirAuto.get_requerir_auto_by_tour (conn, require_vehicle.tour) == null) {
									RequerirAuto.insert_require_vehicle (conn, require_vehicle);
								}
								else {
									RequerirAuto.update_require_vehicle (conn, require_vehicle);
								}
							}
							save_vehicle (null); // Signal the parent to update itself
							this.close ();
						}
						catch (Error e) {
							#if DEBUG
								error (e.message);
							#else
								warning (e.message);
							#endif
						}
					}
					else {
						// Send it to the parent, only insert tuple if tour gets created
						save_vehicle (require_vehicle); // Signal the parent to update itself
						this.close ();
					}
				}
			}
			else if (button == cancel) {
				this.close ();
			}
		}

		/**
		 * Update the the vehicle object with new info from the editor
		 * @return Returns false if the data is invalid
		 */
		private bool update_vehicle_instance () {
			if (vehicle.get_active () > 0) {
				require_vehicle.chofer = chofer.get_text ().strip ();
				Vehiculo new_vehicle;
				Gtk.TreeIter iter;
				vehicle.get_active_iter (out iter);
				vehicle_list_store.get (iter,
					Column.VEHICLE, out new_vehicle);
				if (!validate_vehicle_data ()) {
					return false;
				}
				require_vehicle.vehiculo = new_vehicle;
			}
			else {
				require_vehicle.vehiculo = new Vehiculo ();
				require_vehicle.chofer = "";
			}
			return true;
		}

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

		/**
		 * Initialize what is needed for this window
		 */
		public void initialize () {
			try {
				vehicles = Vehiculo.get_all_vehiculos (conn);
				require_vehicle = RequerirAuto.get_requerir_auto_by_tour (conn, tour);
				if (require_vehicle == null) {
					require_vehicle = new RequerirAuto ("", tour, new Vehiculo ());
				}
			}
			catch (Error e) {
				#if DEBUG
					error (e.message);
				#else
					warning (e.message);
				#endif
			}

			vehicles.sort_with_data ((a, b) => {
				if (a.capacidad < b.capacidad) {
					return -1;
				}
				else if (a.capacidad == b.capacidad) {
					return 0;
				}
				else {
					return 1;
				}
			});

			vehicle_list_store = new Gtk.ListStore (Column.N_COLUMNS,
				typeof (string),
				typeof (Vehiculo));

			vehicle.set_model (vehicle_list_store);

			Gtk.TreeIter iter;
			vehicle_list_store.append (out iter);
			vehicle_list_store.set (iter,
				Column.VEHICLE_DETAILS, _ ("Unassigned"),
				Column.VEHICLE, new Vehiculo ());
			vehicle.set_active (0);
			vehicles.foreach ((entry) => {
				vehicle_list_store.append (out iter);
				vehicle_list_store.set (iter,
					Column.VEHICLE_DETAILS, entry.patente + " " + entry.marca + " " + entry.ano_vehiculo.to_string () + " " + entry.capacidad.to_string (),
					Column.VEHICLE, entry);
				if (require_vehicle.vehiculo.patente.strip () != "" && entry.patente == require_vehicle.vehiculo.patente) {
					vehicle.set_active_iter (iter);
					chofer.set_text (require_vehicle.chofer);
					chofer.sensitive = true;
				}
			});
		}
	}
}
