/*
 * 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/asociado.list.ui")]
	public class AsociadoList : Gtk.ApplicationWindow {
		private Connection conn;
		private enum Column {
			CURSO,
			ASIGNATURA,
			ASOCIADO,
			N_COLUMNS
		}
		private Gtk.ListStore list_store;
		private List<Asociado> asociado_list;

		[GtkChild]
		private Gtk.TreeView asociado_tree;

		[GtkChild]
		private Gtk.Button new_asociado;

		[GtkChild]
		private Gtk.Button edit_asociado;

		[GtkChild]
		private Gtk.Button delete_asociado;

		[GtkChild]
		private Gtk.Button close_asociado;

		[GtkChild]
		private Gtk.TreeViewColumn curso;

		[GtkChild]
		private Gtk.TreeViewColumn asignatura;

		[GtkChild]
		private Gtk.TreeSelection selection;

		public AsociadoList (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_asociado) {
				this.close ();
			}
			if (button == new_asociado) {
				var asociado_editor = new AsociadoEditor (application, conn, null);
				asociado_editor.set_transient_for (this); // Set this window as the parent of the new window
				asociado_editor.initialize ();
				asociado_editor.show_all ();
				asociado_editor.save_asociado.connect (on_save);
			}
			else if (button == edit_asociado) {
				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 ());
					Asociado asociado;
					model.get (iter,
						Column.ASOCIADO, out asociado);
					var asociado_editor = new AsociadoEditor (application, conn, asociado);
					asociado_editor.set_transient_for (this); // Set this window as the parent of the new window
					asociado_editor.initialize ();
					asociado_editor.show_all ();
					asociado_editor.save_asociado.connect (on_save);
				});
			}
			else if (button == delete_asociado) {
				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 curso?");
				}
				else {
					msg = new Gtk.MessageDialog (this,
						Gtk.DialogFlags.MODAL,
						Gtk.MessageType.ERROR,
						Gtk.ButtonsType.YES_NO,
						"¿Está seguro que quiere eliminar estos cursos?");
				}
				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 ());
								Asociado asociado;
								model.get (iter,
									Column.ASOCIADO, out asociado);
								try {
									var res = conn.db.exec ("
DELETE FROM asociado
WHERE id_curso = '" + conn.escape (asociado.curso.id_curso) + "' AND
id_asignatura = " + asociado.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_asociado.sensitive = false;
							delete_asociado.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_asociado.sensitive = true;
				delete_asociado.sensitive =true;
			}
			else if (selection.count_selected_rows () > 1) {
				edit_asociado.sensitive = false;
				delete_asociado.sensitive = true;
			}
			else {
				edit_asociado.sensitive = false;
				delete_asociado.sensitive = false;
			}
		}

		[GtkCallback]
		private void on_clicked_column (Gtk.TreeViewColumn column) {
			edit_asociado.sensitive = false;
			delete_asociado.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;
				}

				asociado_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 == curso) {
				if (!curso.sort_indicator) {
					reset_columns ();
					curso.sort_indicator = true;
				}

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

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

			list_store.clear ();
			asociado_list.foreach ((entry) => {
				Gtk.TreeIter iter;
				list_store.append (out iter);
				list_store.set (iter,
					Column.CURSO, entry.curso.id_curso,
					Column.ASIGNATURA, entry.asignatura.nombre,
					Column.ASOCIADO, entry);
			});
		}

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

		public void on_save(AsociadoEditor asociado_editor) {
			edit_asociado.sensitive = false;
			delete_asociado.sensitive = false;
			reset_columns ();

			list_store.clear ();

			update_list_store ();
		}

		private void update_list_store () {
			var res = conn.db.exec ("
SELECT C.id_curso, C.nombre AS nombre_curso,
	A2.id_asignatura, A2.nombre AS nombre_asignatura
FROM asociado A
JOIN curso C on (C.id_curso = A.id_curso)
JOIN asignatura A2 on (A2.id_asignatura = A.id_asignatura)
			");
			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);
				asociado_list = new List<Asociado> ();
				int n = res.get_n_tuples ();
				for (int i = 0; i < n; i++) {
					try {
						var result = new Asociado (
							new Curso (
								wra.get_string_n (i, "id_curso"),
								wra.get_string_n (i, "nombre_curso")
							),
							new Asignatura (
								wra.get_int_n (i, "id_asignatura"),
								wra.get_string_n (i, "nombre_asignatura")
							)
						);
						asociado_list.append (result);
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
				}

				asociado_list.foreach ((entry) => {
					Gtk.TreeIter iter;
					list_store.append (out iter);
					list_store.set (iter,
						Column.CURSO, entry.curso.id_curso,
						Column.ASIGNATURA, entry.asignatura.nombre,
						Column.ASOCIADO, entry);
				});
			}
		}

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

			update_list_store ();

			asociado_tree.set_model (list_store);
		}
	}
}
