/*
 * 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 editor window class
	 */
	[GtkTemplate (ui = "/cl/cromer/ubb/sernatur/tour.editor.ui")]
	public class TourEditor : Gtk.ApplicationWindow {
		/**
		 * The open database connection
		 */
		private Connection conn;
		/**
		 * The tour to edit
		 */
		private Tour tour;
		/**
		 * The city data stored in the list store
		 */
		private enum CityColumn {
			/**
			 * The city name
			 */
			CITY_NAME,
			/**
			 * The city object
			 */
			CITY,
			/**
			 * The number of colums in this enum
			 */
			N_COLUMNS
		}
		/**
		 * The region data stored in the list store
		 */
		private enum RegionColumn {
			/**
			 * The region name
			 */
			REGION_NAME,
			/**
			 * The region object
			 */
			REGION,
			/**
			 * The number of colums in this enum
			 */
			N_COLUMNS
		}
		/**
		 * The tour name
		 */
		[GtkChild]
		private Gtk.Entry tour_name;
		/**
		 * The individual cost
		 */
		[GtkChild]
		private Gtk.Entry indiv_cost;
		/**
		 * The group cost
		 */
		[GtkChild]
		private Gtk.Entry group_cost;
		/**
		 * The minimum number of people
		 */
		[GtkChild]
		private Gtk.SpinButton minimum_people;
		/**
		 * The region
		 */
		[GtkChild]
		private Gtk.ComboBoxText region;
		/**
		 * The save button
		 */
		[GtkChild]
		private Gtk.Button save;
		/**
		 * The cancel button
		 */
		[GtkChild]
		private Gtk.Button cancel;
		/**
		 * The city
		 */
		[GtkChild]
		private Gtk.ComboBoxText city;
		/**
		 * The city entry
		 */
		[GtkChild]
		private Gtk.Entry city_entry;
		/**
		 * A list of the cities from the database
		 */
		private List<Ciudad> cities;
		/**
		 * A list of the regions from the database
		 */
		private List<Region> regions;
		/**
		 * The list that stores the regions for the combo box
		 */
		private Gtk.ListStore region_list_store;
		/**
		 * The list that stores the cities for the combo box
		 */
		private Gtk.ListStore city_list_store = null;
		/**
		 * This signal is called when a tour is saved
		 */
		public signal void save_tour ();

		[GtkCallback]
		public void on_changed_combobox (Gtk.ComboBox combobox) {
			if (combobox == region) {
				Gtk.TreeIter iter;
				region.get_active_iter (out iter);
				Region temp_region;
				if (region_list_store.iter_is_valid (iter)) {
					region_list_store.get (iter,
						RegionColumn.REGION, out temp_region);
					tour.ciudad.region = temp_region;
					if (city_list_store != null && tour.ciudad.region.id_region != 0) {
						reset_city ();
					}
				}
				else {
					// New region to be created
				}
			}
		}

		private void reset_city () {
			cities = Ciudad.get_all_ciudades_in_region (conn.db, tour.ciudad.region.id_region);

			if (cities.length () > 0) {
				cities.sort_with_data ((a, b) => {
					return strcmp (a.nombre_ciudad, b.nombre_ciudad);
				});

				if (city_list_store.iter_n_children (null) > 0) {
					// If there are more than 0 rows clear it
					city_list_store.clear ();
				}
				cities.foreach ((entry) => {
					Gtk.TreeIter iter;
					city_list_store.append (out iter);
					city_list_store.set (iter,
						CityColumn.CITY_NAME, entry.nombre_ciudad,
						CityColumn.CITY, entry);
					if (tour.ciudad.id_ciudad == 0) {
						tour.ciudad.id_ciudad = entry.id_ciudad;
						tour.ciudad.nombre_ciudad = entry.nombre_ciudad;
					}
					else {
						if (entry.id_ciudad == tour.ciudad.id_ciudad) {
							city.set_active_iter (iter);
						}
					}
				});
			}

			city.set_active (-1);
			city_entry.set_text ("");
		}

		/**
		 * 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 (tour.id_tour == 0) {
					print (city.get_active_text () + "\n");
					Gtk.TreeIter iter;
					Ciudad ciudad;
					city.get_active_iter (out iter);
					if (city_list_store.iter_is_valid (iter)) {
						city_list_store.get (iter,
							CityColumn.CITY, out ciudad);
						print (ciudad.nombre_ciudad + "\n");
					}
				}
				else {
					tour.nombre_tour = tour_name.get_text ();
					tour.costo_indiv = (uint) int.parse (indiv_cost.get_text ());
					tour.costo_grupal = (uint) int.parse (group_cost.get_text ());
					tour.minima_personas = (uint) minimum_people.get_value_as_int ();
					try {
						Tour.update_tour (conn.db, tour);
						save_tour ();
						this.close ();
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
				}
			}
			else if (button == cancel) {
				this.close ();
			}
		}

		/**
		 * 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 TourEditor (Gtk.Application application, Connection conn, Tour? tour) {
			GLib.Object (application: application);
			this.conn = conn;
			this.tour = tour;
		}

		/**
		 * Initialize what is needed for this window
		 */
		public void initialize () {
			regions = Region.get_all_regiones (conn.db);

			regions.sort_with_data ((a, b) => {
				return strcmp (a.nombre_region, b.nombre_region);
			});

			region_list_store = new Gtk.ListStore (RegionColumn.N_COLUMNS,
				typeof (string),
				typeof (Region));

			region.set_model (region_list_store);

			if (tour != null) {
				tour_name.set_text (tour.nombre_tour);
				indiv_cost.set_text (tour.costo_indiv.to_string ());
				group_cost.set_text (tour.costo_grupal.to_string ());
				minimum_people.set_value (tour.minima_personas);
			}
			else {
				tour = new Tour ();
				tour.ciudad = new Ciudad ();
				tour.ciudad.region = new Region ();
			}

			regions.foreach ((entry) => {
				Gtk.TreeIter iter;
				region_list_store.append (out iter);
				region_list_store.set (iter,
					RegionColumn.REGION_NAME, entry.nombre_region,
					RegionColumn.REGION, entry);
				if (entry.id_region == tour.ciudad.region.id_region) {
					region.set_active_iter (iter);
				}
			});

			region.set_entry_text_column (RegionColumn.REGION_NAME);

			city_list_store = new Gtk.ListStore (CityColumn.N_COLUMNS,
				typeof (string),
				typeof (Ciudad));

			city.set_model (city_list_store);

			cities = Ciudad.get_all_ciudades_in_region (conn.db, tour.ciudad.region.id_region);

			if (cities.length () > 0) {
				cities.sort_with_data ((a, b) => {
					return strcmp (a.nombre_ciudad, b.nombre_ciudad);
				});

				cities.foreach ((entry) => {
					Gtk.TreeIter iter;
					city_list_store.append (out iter);
					city_list_store.set (iter,
						CityColumn.CITY_NAME, entry.nombre_ciudad,
						CityColumn.CITY, entry);
					if (entry.id_ciudad == tour.ciudad.id_ciudad) {
						city.set_active_iter (iter);
					}
				});
			}
		}
	}
}
