/*
 * Copyright 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 Colegio {
	using Constants;
	using Misc;
	using DB;
	using DB.Wrapper;
	using Postgres;

	[GtkTemplate (ui = "/cl/cromer/ubb/colegio/horario.list.ui")]
	public class HorarioList : Gtk.ApplicationWindow {
		private Connection conn;
		private enum Column {
			ASIGNATURA,
			BLOQUE,
			SALA,
			HORARIO,
			N_COLUMNS
		}
		private Gtk.ListStore list_store;
		private List<Horario> horario_list;

		[GtkChild]
		private Gtk.TreeView horario_tree;

		[GtkChild]
		private Gtk.Button new_horario;

		[GtkChild]
		private Gtk.Button edit_horario;

		[GtkChild]
		private Gtk.Button delete_horario;

		[GtkChild]
		private Gtk.Button close_horario;

		[GtkChild]
		private Gtk.TreeViewColumn asignatura;

		[GtkChild]
		private Gtk.TreeViewColumn bloque;

		[GtkChild]
		private Gtk.TreeViewColumn sala;

		[GtkChild]
		private Gtk.TreeSelection selection;

		public HorarioList (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
		}

		[GtkCallback]
		public void on_clicked_button (Gtk.Button button) {
			if (button == close_horario) {
				this.close ();
			}
			if (button == new_horario) {
				var horario_editor = new HorarioEditor (application, conn, null);
				horario_editor.set_transient_for (this); // Set this window as the parent of the new window
				horario_editor.initialize ();
				horario_editor.show_all ();
				horario_editor.save_horario.connect (on_save);
			}
			else if (button == edit_horario) {
				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 ());
					Horario horario;
					model.get (iter,
						Column.HORARIO, out horario);
					var horario_editor = new HorarioEditor (application, conn, horario);
					horario_editor.set_transient_for (this); // Set this window as the parent of the new window
					horario_editor.initialize ();
					horario_editor.show_all ();
					horario_editor.save_horario.connect (on_save);
				});
			}
			else if (button == delete_horario) {
				Gtk.MessageDialog msg;
				if (selection.count_selected_rows () == 1) {
					msg = new Gtk.MessageDialog (this,
						Gtk.DialogFlags.MODAL,
						Gtk.MessageType.ERROR,
						Gtk.ButtonsType.YES_NO,
						"¿Está seguro que quiere eliminar este horario?");
				}
				else {
					msg = new Gtk.MessageDialog (this,
						Gtk.DialogFlags.MODAL,
						Gtk.MessageType.ERROR,
						Gtk.ButtonsType.YES_NO,
						"¿Está seguro que quiere eliminar estos horarios?");
				}
				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 ());
								Horario horario;
								model.get (iter,
									Column.HORARIO, out horario);
								var res = conn.db.exec ("
DELETE FROM horario
WHERE id_asignatura = " + horario.asignatura.id_asignatura.to_string () + " AND
id_bloque = " + horario.bloque.id_bloque.to_string ());
								if (res.get_status () != ExecStatus.COMMAND_OK) {
									#if DEBUG
										error (conn.db.get_error_message ());
									#else
										warning (conn.db.get_error_message ());
									#endif
								}
							});
							edit_horario.sensitive = false;
							delete_horario.sensitive = false;
							reset_columns ();

							list_store.clear ();

							update_list_store ();
							break;
					}
					msg.destroy ();
				});
				msg.show ();
			}
		}

		[GtkCallback]
		private void on_changed_selection(Gtk.TreeSelection selection) {
			if (selection.count_selected_rows () == 1) {
				edit_horario.sensitive = true;
				delete_horario.sensitive =true;
			}
			else if (selection.count_selected_rows () > 1) {
				edit_horario.sensitive = false;
				delete_horario.sensitive = true;
			}
			else {
				edit_horario.sensitive = false;
				delete_horario.sensitive = false;
			}
		}

		[GtkCallback]
		private void on_clicked_column (Gtk.TreeViewColumn column) {
			edit_horario.sensitive = false;
			delete_horario.sensitive = false;
			if (column == asignatura) {
				if (!asignatura.sort_indicator) {
					reset_columns ();
					asignatura.sort_indicator = true;
				}

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

				horario_list.sort_with_data ((a, b) => {
					if (asignatura.sort_order == Gtk.SortType.ASCENDING) {
						return strcmp (a.asignatura.nombre, b.asignatura.nombre);
					}
					else {
						return strcmp (b.asignatura.nombre, a.asignatura.nombre);
					}
				});
			}
			else if (column == bloque) {
				if (!bloque.sort_indicator) {
					reset_columns ();
					bloque.sort_indicator = true;
				}

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

				horario_list.sort_with_data ((a, b) => {
					if (bloque.sort_order == Gtk.SortType.ASCENDING) {
						return strcmp (a.bloque.descripcion, b.bloque.descripcion);
					}
					else {
						return strcmp (b.bloque.descripcion, a.bloque.descripcion);
					}
				});
			}
			else if (column == sala) {
				if (!sala.sort_indicator) {
					reset_columns ();
					sala.sort_indicator = true;
				}

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

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

			list_store.clear ();
			horario_list.foreach ((entry) => {
				Gtk.TreeIter iter;
				list_store.append (out iter);
				list_store.set (iter,
					Column.ASIGNATURA, entry.asignatura.nombre,
					Column.BLOQUE, entry.bloque.descripcion,
					Column.SALA, entry.sala,
					Column.HORARIO, entry);
			});
		}

		private void reset_columns () {
			asignatura.sort_indicator = false;
			asignatura.sort_order = Gtk.SortType.DESCENDING;
			bloque.sort_indicator = false;
			bloque.sort_order = Gtk.SortType.DESCENDING;
			sala.sort_indicator = false;
			sala.sort_order = Gtk.SortType.DESCENDING;
		}

		public void on_save(HorarioEditor horario_editor) {
			edit_horario.sensitive = false;
			delete_horario.sensitive = false;
			reset_columns ();

			list_store.clear ();

			update_list_store ();
		}

		private void update_list_store () {
			var res = conn.db.exec ("
SELECT H.sala,
	A.id_asignatura, A.nombre,
	B.id_bloque, B.descripcion
FROM horario H
JOIN asignatura A on (A.id_asignatura = H.id_asignatura)
JOIN bloque B on (B.id_bloque = H.id_bloque)
			");
			if (res.get_status () != ExecStatus.TUPLES_OK) {
				#if DEBUG
					error (conn.db.get_error_message ());
				#else
					warning (conn.db.get_error_message ());
				#endif
			}
			else {
				var wra = new ResultWrapper (res);
				horario_list = new List<Horario> ();
				int n = res.get_n_tuples ();
				for (int i = 0; i < n; i++) {
					try {
						var result = new Horario (
							new Asignatura (
								wra.get_int_n (i, "id_asignatura"),
								wra.get_string_n (i, "nombre")
							),
							new Bloque (
								wra.get_int_n (i, "id_bloque"),
								wra.get_string_n (i, "descripcion")
							),
							wra.get_string_n (i, "sala")
						);
						horario_list.append (result);
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
				}

				horario_list.foreach ((entry) => {
					Gtk.TreeIter iter;
					list_store.append (out iter);
					list_store.set (iter,
						Column.ASIGNATURA, entry.asignatura.nombre,
						Column.BLOQUE, entry.bloque.descripcion,
						Column.SALA, entry.sala,
						Column.HORARIO, entry);
				});
			}
		}

		public void initialize () {
			list_store = new Gtk.ListStore (Column.N_COLUMNS,
				typeof (string),
				typeof (string),
				typeof (string),
				typeof (Horario));

			update_list_store ();

			horario_tree.set_model (list_store);
		}
	}
}
