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

	/**
	 * The tourist list window class
	 */
	[GtkTemplate (ui = "/cl/cromer/ubb/sernatur/tourist.list.ui")]
	public class TouristList : Gtk.ApplicationWindow {
		/**
		 * The open database connection
		 */
		private Connection conn;
		/**
		 * The columns of the tree view
		 */
		private enum Column {
			/**
			 * The tourist's run
			 */
			RUN,
			/**
			 * The tourist's name
			 */
			NAME,
			/**
			 * The tourist's birthdate
			 */
			BIRTHDATE,
			/**
			 * The tourist object
			 */
			TOURIST,
			/**
			 * The number of colums in this enum
			 */
			N_COLUMNS
		}
		/**
		 * The list that stores the contents in the tree view
		 */
		private Gtk.ListStore list_store;
		/**
		 * The list of tourists
		 */
		private List<Turista> tourist_list;
		/**
		 * The tree view widget
		 */
		[GtkChild]
		private Gtk.TreeView tourist_tree;
		/**
		 * Thew new tourist button
		 */
		[GtkChild]
		private Gtk.Button new_tourist;
		/**
		 * The edit tourist button
		 */
		[GtkChild]
		private Gtk.Button edit_tourist;
		/**
		 * The delete tourist button
		 */
		[GtkChild]
		private Gtk.Button delete_tourist;
		/**
		 * The close tourist button
		 */
		[GtkChild]
		private Gtk.Button close_tourist;
		/**
		 * The tourist's RUN
		 */
		[GtkChild]
		private Gtk.TreeViewColumn run;
		/**
		 * The tourist's name
		 */
		[GtkChild]
		private Gtk.TreeViewColumn tourist_name;
		/**
		 * The birthdate
		 */
		[GtkChild]
		private Gtk.TreeViewColumn birthdate;
		/**
		 * The row selection
		 */
		[GtkChild]
		private Gtk.TreeSelection selection;

		/**
		 * This callback is called when the user clicks on a row
		 * @param selection The selection object
		 */
		[GtkCallback]
		private void on_changed_selection(Gtk.TreeSelection selection) {
			if (selection.count_selected_rows () == 1) {
				edit_tourist.sensitive = true;
				delete_tourist.sensitive =true;
			}
			else if (selection.count_selected_rows () > 1) {
				edit_tourist.sensitive = false;
				delete_tourist.sensitive = true;
			}
			else {
				edit_tourist.sensitive = false;
				delete_tourist.sensitive = false;
			}
		}

		/**
		 * This callback is run when the user clicks on a button
		 * @param button The button that was clicked
		 */
		[GtkCallback]
		private void on_clicked_button (Gtk.Button button) {
			if (button == new_tourist) {
				var tourist_editor = new TouristEditor (application, conn, null);
				tourist_editor.set_transient_for (this); // Set this window as the parent of the new window
				tourist_editor.initialize ();
				tourist_editor.show_all ();
				tourist_editor.save_tourist.connect (on_save);
			}
			else if (button == edit_tourist) {
				Gtk.TreeModel model;
				var path = selection.get_selected_rows (out model);
				path.foreach ((entry) => {
					var tree_row_reference = new Gtk.TreeRowReference (model, entry);
					Gtk.TreeIter iter;
					list_store.get_iter (out iter, tree_row_reference.get_path ());
					Turista tourist;
					model.get (iter,
						Column.TOURIST, out tourist);
					var tourist_editor = new TouristEditor (application, conn, tourist);
					tourist_editor.set_transient_for (this); // Set this window as the parent of the new window
					tourist_editor.initialize ();
					tourist_editor.show_all ();
					tourist_editor.save_tourist.connect (on_save);
				});
			}
			else if (button == delete_tourist) {
				Gtk.MessageDialog msg;
				if (selection.count_selected_rows () == 1) {
					msg = new Gtk.MessageDialog (this,
						Gtk.DialogFlags.MODAL,
						Gtk.MessageType.ERROR,
						Gtk.ButtonsType.YES_NO,
						_ ("Are you sure you wish to delete this tourist?"));
				}
				else {
					msg = new Gtk.MessageDialog (this,
						Gtk.DialogFlags.MODAL,
						Gtk.MessageType.ERROR,
						Gtk.ButtonsType.YES_NO,
						_ ("Are you sure you wish to delete these tourists?"));
				}
				msg.response.connect ((response_id) => {
					switch (response_id) {
						case Gtk.ResponseType.YES:
							Gtk.TreeModel model;
							var path = selection.get_selected_rows (out model);
							path.foreach ((entry) => {
								var tree_row_reference = new Gtk.TreeRowReference (model, entry);
								Gtk.TreeIter iter;
								list_store.get_iter (out iter, tree_row_reference.get_path ());
								Turista tourist;
								model.get (iter,
									Column.TOURIST, out tourist);
								try {
									Turista.delete_tourist (conn, tourist);
								}
								catch (PostgresError e) {
									#if DEBUG
										error (e.message);
									#else
										warning (e.message);
									#endif
								}
								catch (DBError e) {
									if (e.code == 1) {
										warning (e.message);
										var msg2 = new Gtk.MessageDialog (this,
											Gtk.DialogFlags.MODAL,
											Gtk.MessageType.ERROR,
											Gtk.ButtonsType.CLOSE,
											_ ("Error: Could not delete tourist \"%s\" because there is still information associated with them!"), tourist.nombre_turista);
										msg2.response.connect ((response_id) => {
											msg2.destroy ();
										});
										msg2.set_title (_ ("Error"));
										msg2.run ();
									}
									else {
										#if DEBUG
											error (e.message);
										#else
											warning (e.message);
										#endif
									}
								}
							});
							edit_tourist.sensitive = false;
							delete_tourist.sensitive = false;
							reset_columns ();

							list_store.clear ();

							update_list_store ();
							break;
					}
					msg.destroy ();
				});
				msg.show ();
			}
			else if (button == close_tourist) {
				this.close ();
			}
		}

		/**
		 * Called when a new or old tourist is saved
		 * @param tourist_editor The editor that saved the tourist
		 */
		public void on_save(TouristEditor tourist_editor) {
			edit_tourist.sensitive = false;
			delete_tourist.sensitive = false;
			reset_columns ();

			list_store.clear ();

			update_list_store ();
		}

		/**
		 * This callback is run when the user clicks on a column to reorder the rows
		 * @param column The column that was clicked
		 */
		[GtkCallback]
		private void on_clicked_column (Gtk.TreeViewColumn column) {
			edit_tourist.sensitive = false;
			delete_tourist.sensitive = false;
			if (column == run) {
				if (!run.sort_indicator) {
					reset_columns ();
					run.sort_indicator = true;
				}

				if (run.sort_order == Gtk.SortType.ASCENDING) {
					run.sort_order = Gtk.SortType.DESCENDING;
				}
				else {
					run.sort_order = Gtk.SortType.ASCENDING;
				}

				tourist_list.sort_with_data ((a, b) => {
					if (run.sort_order == Gtk.SortType.ASCENDING) {
						return strcmp (a.rut_turista, b.rut_turista);
					}
					else {
						return strcmp (b.rut_turista, a.rut_turista);
					}
				});
			}
			else if (column == tourist_name) {
				if (!tourist_name.sort_indicator) {
					reset_columns ();
					tourist_name.sort_indicator = true;
				}

				if (tourist_name.sort_order == Gtk.SortType.ASCENDING) {
					tourist_name.sort_order = Gtk.SortType.DESCENDING;
				}
				else {
					tourist_name.sort_order = Gtk.SortType.ASCENDING;
				}

				tourist_list.sort_with_data ((a, b) => {
					if (tourist_name.sort_order == Gtk.SortType.ASCENDING) {
						return strcmp (a.nombre_turista, b.nombre_turista);
					}
					else {
						return strcmp (b.nombre_turista, a.nombre_turista);
					}
				});
			}
			else if (column == birthdate) {
				if (!birthdate.sort_indicator) {
					reset_columns ();
					birthdate.sort_indicator = true;
				}

				if (birthdate.sort_order == Gtk.SortType.ASCENDING) {
					birthdate.sort_order = Gtk.SortType.DESCENDING;
				}
				else {
					birthdate.sort_order = Gtk.SortType.ASCENDING;
				}

				tourist_list.sort_with_data ((a, b) => {
					if (birthdate.sort_order == Gtk.SortType.ASCENDING) {
						return strcmp (a.fecha_nacimento, b.fecha_nacimento);
					}
					else {
						return strcmp (b.fecha_nacimento, a.fecha_nacimento);
					}
				});
			}

			list_store.clear ();
			tourist_list.foreach ((entry) => {
				Gtk.TreeIter iter;
				list_store.append (out iter);
				try {
					list_store.set (iter,
						Column.RUN, new Rut (entry.rut_turista).get_rut (),
						Column.NAME, entry.nombre_turista,
						Column.BIRTHDATE, entry.fecha_nacimento,
						Column.TOURIST, entry);
				}
				catch (Error e) {
					#if DEBUG
						error (e.message);
					#else
						warning (e.message);
					#endif
				}
			});
		}

		/**
		 * Reset the sort indicator and order of all the columns
		 */
		private void reset_columns () {
			run.sort_indicator = false;
			run.sort_order = Gtk.SortType.DESCENDING;
			tourist_name.sort_indicator = false;
			tourist_name.sort_order = Gtk.SortType.DESCENDING;
			birthdate.sort_indicator = false;
			birthdate.sort_order = Gtk.SortType.DESCENDING;
		}

		/**
		 * Update the list store with the data from the database
		 */
		private void update_list_store () {
			try {
				tourist_list = Turista.get_all_turistas (conn);
			}
			catch (Error e) {
				#if DEBUG
					error (e.message);
				#else
					warning (e.message);
				#endif
			}

			tourist_list.foreach ((entry) => {
				Gtk.TreeIter iter;
				list_store.append (out iter);
				try {
					list_store.set (iter,
						Column.RUN, new Rut (entry.rut_turista).get_rut (),
						Column.NAME, entry.nombre_turista,
						Column.BIRTHDATE, entry.fecha_nacimento,
						Column.TOURIST, entry);
				}
				catch (Error e) {
					#if DEBUG
						error (e.message);
					#else
						warning (e.message);
					#endif
				}
			});
		}

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

			this.set_visible (true); // This fixes: Gtk-CRITICAL **: 23:58:22.139: gtk_box_gadget_distribute: assertion 'size >= 0' failed in GtkScrollbar
		}

		/**
		 * Initialize what is needed for this window
		 */
		public void initialize () {
			list_store = new Gtk.ListStore (Column.N_COLUMNS,
				typeof (string),
				typeof (string),
				typeof (string),
				typeof (Turista));

			update_list_store ();

			tourist_tree.set_model (list_store);
		}
	}
}
