/*
 * 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 add place window class
	 */
	[GtkTemplate (ui = "/cl/cromer/ubb/sernatur/tour.place.editor.ui")]
	public class TourPlaceEditor : Gtk.ApplicationWindow {
		/**
		 * The open database connection
		 */
		private Connection conn;
		/**
		 * The place to edit
		 */
		private Asociado asociado;
		/**
		 * The place data stored in the list store
		 */
		private enum Column {
			/**
			 * The place name
			 */
			PLACE_NAME,
			/**
			 * The place object
			 */
			PLACE,
			/**
			 * The number of colums in this enum
			 */
			N_COLUMNS
		}
		/**
		 * The save button
		 */
		[GtkChild]
		private Gtk.Button save;
		/**
		 * The cancel button
		 */
		[GtkChild]
		private Gtk.Button cancel;
		/**
		 * The place
		 */
		[GtkChild]
		private Gtk.ComboBoxText place;
		/**
		 * The arrival year
		 */
		[GtkChild]
		private Gtk.SpinButton year1;
		/**
		 * The arrival month
		 */
		[GtkChild]
		private Gtk.ComboBoxText month1;
		/**
		 * The arrival day
		 */
		[GtkChild]
		private Gtk.SpinButton day1;
		/**
		 * The departure year
		 */
		[GtkChild]
		private Gtk.SpinButton year2;
		/**
		 * The departure month
		 */
		[GtkChild]
		private Gtk.ComboBoxText month2;
		/**
		 * The departure day
		 */
		[GtkChild]
		private Gtk.SpinButton day2;
		/**
		 * The arrival hour
		 */
		[GtkChild]
		private Gtk.SpinButton hour1;
		/**
		 * The arrival minute
		 */
		[GtkChild]
		private Gtk.SpinButton minute1;
		/**
		 * The departure hour
		 */
		[GtkChild]
		private Gtk.SpinButton hour2;
		/**
		 * The departure minute
		 */
		[GtkChild]
		private Gtk.SpinButton minute2;
		/**
		 * A list of the places from the database
		 */
		private List<Lugar> places;
		/**
		 * The list that stores the places for the combo box
		 */
		private Gtk.ListStore places_list_store;
		/**
		 * This signal is called when a place is saved
		 */
		public signal void save_place (Asociado asociado);

		/**
		 * 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 (asociado.tour.id_tour == 0) {
					update_place_instance ();
					if (asociado.lugar.id_lugar != 0) {
						save_place (asociado); // Signal the parent to update itself
						this.close ();
					}
				}
				else if (asociado.fecha_llegada == "") {
					update_place_instance ();
					try {
						Asociado.insert_asociado (conn, asociado);
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
					finally {
						save_place (asociado); // Signal the parent to update itself
						this.close ();
					}
				}
				else {
					// Not implemented due to lack of time
					/*update_place_instance ();
					try {
						Asociado.update_asociado (conn, lugar);
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
					finally {
						save_place (asociado); // Signal the parent to update itself
						this.close ();
					}*/
				}
			}
			else if (button == cancel) {
				this.close ();
			}
		}

		/**
		 * Update the the place object with new info from the editor
		 */
		private void update_place_instance () {
			if (place.get_active () > 0) {
				Lugar lugar;
				Gtk.TreeIter iter;
				place.get_active_iter (out iter);
				if (places_list_store.iter_is_valid (iter)) {
					places_list_store.get (iter,
						Column.PLACE, out lugar);
					asociado.lugar = lugar;
				}
			}

			asociado.fecha_llegada = year1.get_value ().to_string () + "-" +
				(month1.get_active () + 1).to_string () + "-" +
				day1.get_value ().to_string ();

			asociado.hora_llegada = hour1.get_value ().to_string () + ":" +
				minute1.get_value ().to_string () + ":00";

			asociado.fecha_salida = year2.get_value ().to_string () + "-" +
				(month2.get_active () + 1).to_string () + "-" +
				day2.get_value ().to_string ();

			asociado.hora_salida = hour2.get_value ().to_string () + ":" +
				minute2.get_value ().to_string () + ":00";
		}

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

		/**
		 * Initialize what is needed for this window
		 */
		public void initialize () {
			try {
				places = Lugar.get_all_lugares (conn);
			}
			catch (Error e) {
				#if DEBUG
					error (e.message);
				#else
					warning (e.message);
				#endif
			}

			places.sort_with_data ((a, b) => {
				return strcmp (a.nombre_lugar, b.nombre_lugar);
			});

			places_list_store = new Gtk.ListStore (Column.N_COLUMNS,
				typeof (string),
				typeof (Lugar));

			place.set_model (places_list_store);

			if (asociado.fecha_llegada != "") {
				string[] arrival_date = asociado.fecha_llegada.split ("-", 3);
				year1.set_value (double.parse (arrival_date[0]));
				month1.set_active (int.parse (arrival_date[1]) - 1);
				day1.set_value (double.parse (arrival_date[2]));

				string[] departure_date = asociado.fecha_salida.split ("-", 3);
				year2.set_value (double.parse (departure_date[0]));
				month2.set_active (int.parse (departure_date[1]) - 1);
				day2.set_value (double.parse (departure_date[2]));

				string[] arrival_time = asociado.hora_llegada.split (":", 2);
				hour1.set_value (double.parse (arrival_time[0]));
				minute1.set_value (double.parse (arrival_time[1]));

				string[] departure_time = asociado.hora_salida.split (":", 2);
				hour2.set_value (double.parse (departure_time[0]));
				minute2.set_value (double.parse (departure_time[1]));
			}
			else {
				asociado.lugar = new Lugar ();
			}

			places.foreach ((entry) => {
				Gtk.TreeIter iter;
				places_list_store.append (out iter);
				places_list_store.set (iter,
					Column.PLACE_NAME, entry.nombre_lugar,
					Column.PLACE, entry);
				if (entry.id_lugar == asociado.lugar.id_lugar) {
					place.set_active_iter (iter);
				}
			});
		}
	}
}
