/*
 * 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.inscribir.list.ui")]
	public class RegistroInscribirList : Gtk.ApplicationWindow {
		private Connection conn;
		private Asignatura asignatura;

		public signal void save_inscribir ();

		private enum Column {
			RUT,
			NAME,
			ALUMNO,
			N_COLUMNS
		}
		private Gtk.ListStore list_store;
		private List<Alumno> alumno_list;

		[GtkChild]
		private Gtk.TreeView alumno_tree;

		[GtkChild]
		private Gtk.Button inscribir;

		[GtkChild]
		private Gtk.Button close_alumno;

		[GtkChild]
		private Gtk.TreeViewColumn rut;

		[GtkChild]
		private Gtk.TreeViewColumn alumno;

		[GtkChild]
		private Gtk.TreeSelection selection;

		public RegistroInscribirList (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 ();
			}
			else if (button == inscribir) {
				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 inscribir este alumno a la asignatura?");
				}
				else {
					msg = new Gtk.MessageDialog (this,
						Gtk.DialogFlags.MODAL,
						Gtk.MessageType.ERROR,
						Gtk.ButtonsType.YES_NO,
						"¿Está seguro que quiere inscribir estos alumnos a 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 ());
								Alumno alumno;
								model.get (iter,
									Column.ALUMNO, out alumno);
									try {
										var res = conn.db.exec ("
INSERT INTO registro
(rut_alumno, id_asignatura, nota)
VALUES
(
'" + conn.escape (alumno.rut_alumno) + "',
'" + asignatura.id_asignatura.to_string () + "',
'1.0'
)
										");
										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
									}
									finally {
										save_inscribir (); // Signal the parent to update itself
										this.close ();
									}
							});
							break;
					}
					msg.destroy ();
				});
				msg.show ();
			}
		}

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

		[GtkCallback]
		private void on_clicked_column (Gtk.TreeViewColumn column) {
			inscribir.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;
				}

				alumno_list.sort_with_data ((a, b) => {
					if (alumno.sort_order == Gtk.SortType.ASCENDING) {
						return strcmp (a.nombres, b.nombres);
					}
					else {
						return strcmp (b.nombres, a.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;
				}

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

			list_store.clear ();
			alumno_list.foreach ((entry) => {
				Gtk.TreeIter iter;
				list_store.append (out iter);
				try {
					list_store.set (iter,
						Column.RUT, new Misc.Rut(entry.rut_alumno).get_rut (),
						Column.NAME, entry.nombres + " " + entry.apellidos,
						Column.ALUMNO, 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;
		}

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

				alumno_list.foreach ((entry) => {
					Gtk.TreeIter iter;
					list_store.append (out iter);
					try {
						list_store.set (iter,
							Column.RUT, new Misc.Rut(entry.rut_alumno).get_rut (),
							Column.NAME, entry.nombres + " " + entry.apellidos,
							Column.ALUMNO, 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 (Alumno));

			update_list_store ();

			alumno_tree.set_model (list_store);
		}
	}
}
