/*
 * 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 illness window class
	 */
	[GtkTemplate (ui = "/cl/cromer/ubb/sernatur/tourist.illnesses.ui")]
	public class TouristIllnesses : Gtk.ApplicationWindow {
		/**
		 * The open database connection
		 */
		private Connection conn;
		/**
		 * The tourist to edit
		 */
		private Turista tourist;
		/**
		 * The columns of the tree view
		 */
		private enum Column {
			/**
			 * The illness description
			 */
			ILLNESS_DESCRIPTION,
			/**
			 * The illness object
			 */
			ILLNESS,
			/**
			 * 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 illnesses
		 */
		private List<TieneEnfermedad> illness_list;
		/**
		 * The tree view widget
		 */
		[GtkChild]
		private Gtk.TreeView illness_tree;
		/**
		 * The illness column
		 */
		[GtkChild]
		private Gtk.TreeViewColumn illness;
		/**
		 * The add button
		 */
		[GtkChild]
		private Gtk.Button add_illness;
		/**
		 * The close button
		 */
		[GtkChild]
		private Gtk.Button close_illness;
		/**
		 * The delete button
		 */
		[GtkChild]
		private Gtk.Button delete_illness;
		/**
		 * The row selection
		 */
		[GtkChild]
		private Gtk.TreeSelection selection;
		/**
		 * The associated tours to save if the user decides to save the tour
		 */
		private List<TieneEnfermedad> new_illness_list = new List<TieneEnfermedad> ();

		/**
		 * 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) {
				delete_illness.sensitive =true;
			}
			else if (selection.count_selected_rows () > 1) {
				delete_illness.sensitive = true;
			}
			else {
				delete_illness.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 == add_illness) {
				var illness_editor = new TouristIllnessEditor (application, conn, new TieneEnfermedad (tourist));
				illness_editor.set_transient_for (this); // Set this window as the parent of the new window
				illness_editor.initialize ();
				illness_editor.show_all ();
				illness_editor.save_illness.connect (on_save_tourist_illness);
			}
			else if (button == delete_illness) {
				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 illness from 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 illnesses from this tourist?"));
				}
				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 ());
								TieneEnfermedad has_illness;
								model.get (iter,
									Column.ILLNESS, out has_illness);
								try {
									TieneEnfermedad.delete_illness (conn, has_illness);
								}
								catch (PostgresError e) {
									#if DEBUG
										error (e.message);
									#else
										warning (e.message);
									#endif
								}
							});
							delete_illness.sensitive = false;
							reset_columns ();

							list_store.clear ();

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

		/**
		 * 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) {
			delete_illness.sensitive = false;
			if (column == illness) {
				if (!illness.sort_indicator) {
					reset_columns ();
					illness.sort_indicator = true;
				}

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

				illness_list.sort_with_data ((a, b) => {
					if (illness.sort_order == Gtk.SortType.ASCENDING) {
						return strcmp (a.enfermedad.descripcion_enfermedad, b.enfermedad.descripcion_enfermedad);
					}
					else {
						return strcmp (b.enfermedad.descripcion_enfermedad, a.enfermedad.descripcion_enfermedad);
					}
				});
			}

			list_store.clear ();
			illness_list.foreach ((entry) => {
				Gtk.TreeIter iter;
				list_store.append (out iter);
				list_store.set (iter,
					Column.ILLNESS_DESCRIPTION, entry.enfermedad.descripcion_enfermedad,
					Column.ILLNESS, entry);
			});
			new_illness_list.foreach ((entry) => {
				Gtk.TreeIter iter;
				list_store.append (out iter);
				list_store.set (iter,
					Column.ILLNESS_DESCRIPTION, entry.enfermedad.descripcion_enfermedad,
					Column.ILLNESS, entry);
			});
		}

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

		/**
		 * Called when a illness is saved
		 * @param illness_editor The editor that saved the illness
		 */
		public void on_save_tourist_illness (TouristIllnessEditor illness_editor) {
			reset_columns ();

			list_store.clear ();
			update_list_store ();
		}

		/**
		 * Update the list store with the data from the database
		 */
		private void update_list_store () {
			try {
				illness_list = TieneEnfermedad.get_all_tiene_enfermedades_by_run (conn, tourist.rut_turista);
			}
			catch (Error e) {
				#if DEBUG
					error (e.message);
				#else
					warning (e.message);
				#endif
			}

			illness_list.foreach ((entry) => {
				Gtk.TreeIter iter;
				list_store.append (out iter);
				list_store.set (iter,
					Column.ILLNESS_DESCRIPTION, entry.enfermedad.descripcion_enfermedad,
					Column.ILLNESS, entry);
			});
		}

		/**
		 * Initialize the tour list class
		 * @param application The application used to make the GLib object
		 * @param conn The database connection to use
		 * @param tourist The tourist which is the parent of this window
		 */
		public TouristIllnesses (Gtk.Application application, Connection conn, Turista? tourist) {
			Object (application: application);
			this.conn = conn;
			this.tourist = tourist;

			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 (TieneEnfermedad));

			if (tourist != null) {
				update_list_store ();
			}

			illness_tree.set_model (list_store);
		}
	}
}
