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

	/**
	 * The query window class
	 */
	[GtkTemplate (ui = "/cl/cromer/ubb/sernatur/query.window.ui")]
	public class QueryWindow : Gtk.ApplicationWindow {
		/**
		 * The open database connection
		 */
		private Connection conn;
		/**
		 * The queries that can be called
		 */
		public enum Query {
			/**
			 * The Q1 query
			 */
			Q1,
			/**
			 * The Q2 query
			 */
			Q2,
			/**
			 * The Q3 query
			 */
			Q3,
			/**
			 * The Q4 query
			 */
			Q4,
			/**
			 * The Q5 query
			 */
			Q5
		}
		/**
		 * The query to use in the object
		 */
		private Query query;
		/**
		 * The columns of the Q1 tree view
		 */
		private enum Q1Column {
			/**
			 * The region name
			 */
			REGION_NAME,
			/**
			 * The quantity
			 */
			QUANTITY,
			/**
			 * The number of colums in this enum
			 */
			N_COLUMNS
		}
		/**
		 * The columns of the Q2 tree view
		 */
		private enum Q2Column {
			/**
			 * The tour name
			 */
			TOUR_NAME,
			/**
			 * The total value
			 */
			TOTAL_VALUE,
			/**
			 * The number of colums in this enum
			 */
			N_COLUMNS
		}
		/**
		 * The columns of the Q3 tree view
		 */
		private enum Q3Column {
			/**
			 * The tour name
			 */
			TOUR_NAME,
			/**
			 * The total of coordinators
			 */
			COORDINATOR_TOTAL,
			/**
			 * The number of colums in this enum
			 */
			N_COLUMNS
		}
		/**
		 * The columns of the Q4 tree view
		 */
		private enum Q4Column {
			/**
			 * The tour name
			 */
			TOUR_NAME,
			/**
			 * The total of turists
			 */
			TOURIST_TOTAL,
			/**
			 * The number of colums in this enum
			 */
			N_COLUMNS
		}
		/**
		 * The columns of the Q5 tree view
		 */
		private enum Q5Column {
			/**
			 * The percentage
			 */
			PERCENTAGE,
			/**
			 * 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 scroll window where the columns and rows are stored
		 */
		[GtkChild]
		private Gtk.ScrolledWindow scroll_window;
		/**
		 * The statement label
		 */
		[GtkChild]
		private Gtk.Label statement;
		/**
		 * The sql label
		 */
		[GtkChild]
		private Gtk.Label sql;
		/**
		 * The run button
		 */
		[GtkChild]
		private Gtk.Button run_query;
		/**
		 * The close button
		 */
		[GtkChild]
		private Gtk.Button close_query;
		/**
		 * The query tree
		 */
		private Gtk.TreeView query_tree;

		/**
		 * 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 == run_query) {
				list_store.clear ();
				if (query == Query.Q1) {
					var region_list = Views.Q1.get_regions_without_discount (conn.db);

					region_list.foreach ((entry) => {
						Gtk.TreeIter iter;
						list_store.append (out iter);
						list_store.set (iter,
							Q1Column.REGION_NAME, entry.nombre_region,
							Q1Column.QUANTITY, entry.cantidad);
					});
				}
				else if (query == Query.Q2) {
					var value_list = Views.Q2.get_value_received (conn.db);

					value_list.foreach ((entry) => {
						Gtk.TreeIter iter;
						list_store.append (out iter);
						list_store.set (iter,
							Q2Column.TOUR_NAME, entry.nombre_tour,
							Q2Column.TOTAL_VALUE, Money.format_uint (entry.valor_recibido));
					});
				}
				else if (query == Query.Q3) {
					var value_list = Views.Q3.get_total_coordinators (conn.db);

					value_list.foreach ((entry) => {
						Gtk.TreeIter iter;
						list_store.append (out iter);
						list_store.set (iter,
							Q3Column.TOUR_NAME, entry.nombre_tour,
							Q3Column.COORDINATOR_TOTAL, entry.total_coordinadores);
					});
				}
				else if (query == Query.Q4) {
					var value_list = Views.Q4.get_total_tourists (conn.db);

					value_list.foreach ((entry) => {
						Gtk.TreeIter iter;
						list_store.append (out iter);
						list_store.set (iter,
							Q4Column.TOUR_NAME, entry.nombre_tour,
							Q4Column.TOURIST_TOTAL, entry.total_turistas);
					});
				}
				else if (query == Query.Q5) {
					var value_list = Views.Q5.get_percentage (conn.db);

					value_list.foreach ((entry) => {
						Gtk.TreeIter iter;
						list_store.append (out iter);
						list_store.set (iter,
							Q5Column.PERCENTAGE, Percentage.format_float (entry.porcentaje));
					});
				}
			}
			else if (button == close_query) {
				this.close ();
			}
		}

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

			// Load scroll window's content
			var builder = new Gtk.Builder ();
			try {
				builder.add_from_resource ("/cl/cromer/ubb/sernatur/query.tree.ui");
				builder.connect_signals (null);
				if (query == Query.Q1) {
					query_tree = builder.get_object ("query_tree_q1") as Gtk.TreeView;
				}
				else if (query == Query.Q2) {
					query_tree = builder.get_object ("query_tree_q2") as Gtk.TreeView;
				}
				else if (query == Query.Q3) {
					query_tree = builder.get_object ("query_tree_q3") as Gtk.TreeView;
				}
				else if (query == Query.Q4) {
					query_tree = builder.get_object ("query_tree_q4") as Gtk.TreeView;
				}
				else if (query == Query.Q5) {
					query_tree = builder.get_object ("query_tree_q5") as Gtk.TreeView;
				}
				query_tree.set_visible (true);

				// Add logo to scroll window
				scroll_window.add (query_tree);
			}
			catch (Error e) {
				// This error is not fatal, so let's keep going
				warning (e.message);
			}

			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 () {
			if (query == Query.Q1) {
				this.set_title (dgettext (null, "(Q1) Regions with discounts"));

				list_store = new Gtk.ListStore (Q1Column.N_COLUMNS,
					typeof (string),
					typeof (uint));

				query_tree.set_model (list_store);

				statement.set_text (Q1_STATEMENT);

				sql.set_text (Q1_SQL);
			}
			else if (query == Query.Q2) {
				this.set_title (dgettext (null, "(Q2) Tour values"));

				list_store = new Gtk.ListStore (Q2Column.N_COLUMNS,
					typeof (string),
					typeof (string));

				query_tree.set_model (list_store);

				statement.set_text (Q2_STATEMENT);

				sql.set_text (Q2_SQL);
			}
			else if (query == Query.Q3) {
				this.set_title (dgettext (null, "(Q3) Coordinator total"));

				list_store = new Gtk.ListStore (Q3Column.N_COLUMNS,
					typeof (string),
					typeof (uint));

				query_tree.set_model (list_store);

				statement.set_text (Q3_STATEMENT);

				sql.set_text (Q3_SQL);
			}
			else if (query == Query.Q4) {
				this.set_title (dgettext (null, "(Q4) Tourist total"));

				list_store = new Gtk.ListStore (Q4Column.N_COLUMNS,
					typeof (string),
					typeof (uint));

				query_tree.set_model (list_store);

				statement.set_text (Q4_STATEMENT);

				sql.set_text (Q4_SQL);
			}
			else if (query == Query.Q5) {
				this.set_title (dgettext (null, "(Q5) Vehicle total"));

				list_store = new Gtk.ListStore (Q5Column.N_COLUMNS,
					typeof (string));

				query_tree.set_model (list_store);

				statement.set_text (Q5_STATEMENT);

				sql.set_text (Q5_SQL);
			}
		}
	}
}
