/*
 * 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/registro.alumno.list.ui")]
	public class RegistroAlumnoList : Gtk.ApplicationWindow {
		private Connection conn;
		private Asignatura asignatura;
		private enum Column {
			RUT,
			NAME,
			NOTA,
			REGISTRO,
			N_COLUMNS
		}
		private Gtk.ListStore list_store;
		private List<Registro> registro_list;

		[GtkChild]
		private Gtk.TreeView alumno_tree;

		[GtkChild]
		private Gtk.Button add_alumno;

		[GtkChild]
		private Gtk.Button edit_alumno;

		[GtkChild]
		private Gtk.Button delete_alumno;

		[GtkChild]
		private Gtk.Button close_alumno;

		[GtkChild]
		private Gtk.TreeViewColumn rut;

		[GtkChild]
		private Gtk.TreeViewColumn alumno;

		[GtkChild]
		private Gtk.TreeViewColumn nota;

		[GtkChild]
		private Gtk.TreeSelection selection;

		public RegistroAlumnoList (Gtk.Application application, Connection conn, Asignatura asignatura) {
			Object (application: application);
			this.conn = conn;
			this.asignatura = asignatura;

			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_alumno) {
				this.close ();
			}
			if (button == edit_alumno) {
				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 ());
					Registro registro;
					model.get (iter,
						Column.REGISTRO, out registro);
					var registro_alumno_edit = new RegistroAlumnoEdit (application, conn, registro);
					registro_alumno_edit.set_transient_for (this); // Set this window as the parent of the new window
					registro_alumno_edit.initialize ();
					registro_alumno_edit.show_all ();
					registro_alumno_edit.save_nota.connect (on_save);
				});
			}
			else if (button == add_alumno) {
				var registro_inscribir_list = new RegistroInscribirList (application, conn, asignatura);
				registro_inscribir_list.set_transient_for (this); // Set this window as the parent of the new window
				registro_inscribir_list.initialize ();
				registro_inscribir_list.show_all ();
				registro_inscribir_list.save_inscribir.connect (on_save_inscribir);
			}
			else if (button == delete_alumno) {
				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 alumno de la asignatura?");
				}
				else {
					msg = new Gtk.MessageDialog (this,
						Gtk.DialogFlags.MODAL,
						Gtk.MessageType.ERROR,
						Gtk.ButtonsType.YES_NO,
						"¿Está seguro que quiere eliminar estos alumnos de la asignatura?");
				}
				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 ());
								Registro registro;
								model.get (iter,
									Column.REGISTRO, out registro);
									try {
										var res = conn.db.exec ("
DELETE FROM registro
WHERE rut_alumno = '" + conn.escape (registro.alumno.rut_alumno) + "' AND
id_asignatura = " + registro.asignatura.id_asignatura.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
										}
									}
									catch (PostgresError e) {
										#if DEBUG
											error (e.message);
										#else
											warning (e.message);
										#endif
									}
							});
							edit_alumno.sensitive = false;
							delete_alumno.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_alumno.sensitive = true;
				delete_alumno.sensitive = true;
			}
			else if (selection.count_selected_rows () > 1) {
				edit_alumno.sensitive = false;
				delete_alumno.sensitive = true;
			}
			else {
				edit_alumno.sensitive = false;
				delete_alumno.sensitive = false;
			}
		}

		[GtkCallback]
		private void on_clicked_column (Gtk.TreeViewColumn column) {
			edit_alumno.sensitive = false;
			delete_alumno.sensitive = false;
			if (column == alumno) {
				if (!alumno.sort_indicator) {
					reset_columns ();
					alumno.sort_indicator = true;
				}

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

				registro_list.sort_with_data ((a, b) => {
					if (alumno.sort_order == Gtk.SortType.ASCENDING) {
						return strcmp (a.alumno.nombres, b.alumno.nombres);
					}
					else {
						return strcmp (b.alumno.nombres, a.alumno.nombres);
					}
				});
			}
			else if (column == rut) {
				if (!rut.sort_indicator) {
					reset_columns ();
					rut.sort_indicator = true;
				}

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

				registro_list.sort_with_data ((a, b) => {
					if (rut.sort_order == Gtk.SortType.ASCENDING) {
						return strcmp (a.alumno.rut_alumno, b.alumno.rut_alumno);
					}
					else {
						return strcmp (b.alumno.rut_alumno, a.alumno.rut_alumno);
					}
				});
			}
			else if (column == nota) {
				if (!nota.sort_indicator) {
					reset_columns ();
					nota.sort_indicator = true;
				}

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

				registro_list.sort_with_data ((a, b) => {
					if (nota.sort_order == Gtk.SortType.ASCENDING) {
						if (a.nota < b.nota) {
							return -1;
						}
						else if (a.nota == b.nota) {
							return 0;
						}
						else {
							return 1;
						}
					}
					else {
						if (a.nota < b.nota) {
							return 1;
						}
						else if (a.nota == b.nota) {
							return 0;
						}
						else {
							return -1;
						}
					}
				});
			}

			list_store.clear ();
			registro_list.foreach ((entry) => {
				Gtk.TreeIter iter;
				list_store.append (out iter);
				try {
					list_store.set (iter,
						Column.RUT, new Misc.Rut(entry.alumno.rut_alumno).get_rut (),
						Column.NAME, entry.alumno.nombres + " " + entry.alumno.apellidos,
						Column.NOTA, entry.nota.to_string("%.1f"),
						Column.REGISTRO, entry);
				}
				catch (InvalidRut e) {
					#if DEBUG
						error (e.message);
					#else
						warning (e.message);
					#endif
				}
			});
		}

		private void reset_columns () {
			alumno.sort_indicator = false;
			alumno.sort_order = Gtk.SortType.DESCENDING;
			rut.sort_indicator = false;
			rut.sort_order = Gtk.SortType.DESCENDING;
			nota.sort_indicator = false;
			nota.sort_order = Gtk.SortType.DESCENDING;
		}

		public void on_save (RegistroAlumnoEdit registro_alumno_edit) {
			edit_alumno.sensitive = false;
			delete_alumno.sensitive = false;
			reset_columns ();

			list_store.clear ();

			update_list_store ();
		}

		public void on_save_inscribir (RegistroInscribirList registro_inscribir_list) {
			edit_alumno.sensitive = false;
			delete_alumno.sensitive = false;
			reset_columns ();

			list_store.clear ();

			update_list_store ();
		}

		private void update_list_store () {
			var res = conn.db.exec ("
SELECT R.nota,
	A.rut_alumno, A.nombres, A.apellidos
FROM registro R
JOIN alumno A ON (A.rut_alumno = R.rut_alumno)
WHERE (R.id_asignatura='" + asignatura.id_asignatura.to_string () + "')
			");
			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);
				registro_list = new List<Registro> ();
				int n = res.get_n_tuples ();
				for (int i = 0; i < n; i++) {
					try {
						var result = new Registro (
							asignatura,
							new Alumno (
								wra.get_string_n (i, "rut_alumno"),
								wra.get_string_n (i, "nombres"),
								wra.get_string_n (i, "apellidos")
							),
							wra.get_float_n (i, "nota")
						);
						registro_list.append (result);
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
				}

				registro_list.foreach ((entry) => {
					Gtk.TreeIter iter;
					list_store.append (out iter);
					try {
						list_store.set (iter,
							Column.RUT, new Misc.Rut(entry.alumno.rut_alumno).get_rut (),
							Column.NAME, entry.alumno.nombres + " " + entry.alumno.apellidos,
							Column.NOTA, entry.nota.to_string("%.1f"),
							Column.REGISTRO, entry);
					}
					catch (InvalidRut e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
				});
			}
		}

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

			update_list_store ();

			alumno_tree.set_model (list_store);
		}
	}
}
