/*
 * 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/asignatura.list.ui")]
	public class AsignaturaList : Gtk.ApplicationWindow {
		private Connection conn;
		private enum Column {
			NAME,
			PROFESOR,
			ASIGNATURA,
			N_COLUMNS
		}
		private Gtk.ListStore list_store;
		private List<Asignatura> asignatura_list;

		[GtkChild]
		private Gtk.TreeView asignatura_tree;

		[GtkChild]
		private Gtk.Button edit_asignatura;

		[GtkChild]
		private Gtk.Button delete_asignatura;

		[GtkChild]
		private Gtk.Button close_asignatura;

		[GtkChild]
		private Gtk.TreeViewColumn asignatura_name;

		[GtkChild]
		private Gtk.TreeViewColumn teacher;

		[GtkChild]
		private Gtk.TreeSelection selection;

		[GtkCallback]
		public void on_clicked_button (Gtk.Button button) {
			if (button == close_asignatura) {
				this.close ();
			}
			else if (button == delete_asignatura) {
				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 esta asignatura?");
				}
				else {
					msg = new Gtk.MessageDialog (this,
						Gtk.DialogFlags.MODAL,
						Gtk.MessageType.ERROR,
						Gtk.ButtonsType.YES_NO,
						"¿Está seguro que quiere eliminar estas asignaturas?");
				}
				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 ());
								Asignatura asignatura;
								model.get (iter,
									Column.ASIGNATURA, out asignatura);
									var res = conn.db.exec ("
DELETE FROM asignatura
WHERE id_asignatura = " + asignatura.id_asignatura.to_string ());
								if (res.get_status () != ExecStatus.COMMAND_OK) {
									if (res.get_error_field (FieldCode.SQLSTATE) == "23503") {
										warning (res.get_error_field (FieldCode.MESSAGE_PRIMARY));
										var msg2 = new Gtk.MessageDialog (this,
											Gtk.DialogFlags.MODAL,
											Gtk.MessageType.ERROR,
											Gtk.ButtonsType.CLOSE,
											"Error: No se puede eleminar la asignatura \"%s\" porque todavia está asociado a cursos, alumnos y actividades!", asignatura.nombre);
										msg2.response.connect ((response_id) => {
											msg2.destroy ();
										});
										msg2.set_title ("Error");
										msg2.run ();
									}
								}
							});
							edit_asignatura.sensitive = false;
							delete_asignatura.sensitive = false;
							reset_columns ();

							list_store.clear ();

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

		public AsignaturaList (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]
		private void on_changed_selection(Gtk.TreeSelection selection) {
			if (selection.count_selected_rows () == 1) {
				edit_asignatura.sensitive = true;
				delete_asignatura.sensitive =true;
			}
			else if (selection.count_selected_rows () > 1) {
				edit_asignatura.sensitive = false;
				delete_asignatura.sensitive = true;
			}
			else {
				edit_asignatura.sensitive = false;
				delete_asignatura.sensitive = false;
			}
		}

		[GtkCallback]
		private void on_clicked_column (Gtk.TreeViewColumn column) {
			edit_asignatura.sensitive = false;
			delete_asignatura.sensitive = false;
			if (column == asignatura_name) {
				if (!asignatura_name.sort_indicator) {
					reset_columns ();
					asignatura_name.sort_indicator = true;
				}

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

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

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

				asignatura_list.sort_with_data ((a, b) => {
					if (teacher.sort_order == Gtk.SortType.ASCENDING) {
						return strcmp (a.profesor.nombres, b.profesor.nombres);
					}
					else {
						return strcmp (b.profesor.nombres, a.profesor.nombres);
					}
				});
			}

			list_store.clear ();
			asignatura_list.foreach ((entry) => {
				Gtk.TreeIter iter;
				list_store.append (out iter);
				list_store.set (iter,
					Column.NAME, entry.nombre,
					Column.PROFESOR, entry.profesor.nombres + " " + entry.profesor.apellidos,
					Column.ASIGNATURA, entry);
			});
		}

		private void reset_columns () {
			asignatura_name.sort_indicator = false;
			asignatura_name.sort_order = Gtk.SortType.DESCENDING;
			teacher.sort_indicator = false;
			teacher.sort_order = Gtk.SortType.DESCENDING;
		}

		private void update_list_store () {
			var res = conn.db.exec ("
SELECT A.id_asignatura, A.nombre,
	P.rut_profesor, P.nombres, P.apellidos
FROM asignatura A
JOIN profesor P ON (P.rut_profesor = A.rut_profesor)
			");
			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);
				asignatura_list = new List<Asignatura> ();
				int n = res.get_n_tuples ();
				for (int i = 0; i < n; i++) {
					try {
						var result = new Asignatura (
							wra.get_int_n (i, "id_asignatura"),
							wra.get_string_n (i, "nombre"),
							new Profesor (
								wra.get_string_n (i, "rut_profesor"),
								wra.get_string_n (i, "nombres"),
								wra.get_string_n (i, "apellidos")
							)
						);
						asignatura_list.append (result);
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
				}

				asignatura_list.foreach ((entry) => {
					Gtk.TreeIter iter;
					list_store.append (out iter);
					list_store.set (iter,
						Column.NAME, entry.nombre,
						Column.PROFESOR, entry.profesor.nombres + " " + entry.profesor.apellidos,
						Column.ASIGNATURA, entry);
				});
			}
		}

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

			update_list_store ();

			asignatura_tree.set_model (list_store);
		}
	}
}
