/*
 * 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.editor.ui")]
	public class HorarioEditor : Gtk.ApplicationWindow {
		private Connection conn;
		private Horario horario;
		private Horario? old_horario = null;

		private List<Asignatura> asignaturas;
		private Gtk.ListStore asignatura_list_store;
		private List<Bloque> bloques;
		private Gtk.ListStore bloque_list_store;

		public signal void save_horario ();

		private enum AsignaturaColumn {
			NAME,
			ASIGNATURA,
			N_COLUMNS
		}
		private enum BloqueColumn {
			DESCRIPCION,
			BLOQUE,
			N_COLUMNS
		}

		[GtkChild]
		private Gtk.ComboBoxText asignatura;

		[GtkChild]
		private Gtk.ComboBoxText bloque;

		[GtkChild]
		private Gtk.Entry sala;

		[GtkChild]
		private Gtk.Button save;

		[GtkChild]
		private Gtk.Button cancel;

		public HorarioEditor (Gtk.Application application, Connection conn, Horario? horario) {
			Object (application: application);
			this.conn = conn;
			this.horario = horario;
			if (this.horario != null) {
				this.old_horario = new Horario ();
				this.old_horario.copy (horario);
			}
		}

		[GtkCallback]
		public void on_clicked_button (Gtk.Button button) {
			if (button == cancel) {
				this.close ();
			}
			else if (button == save) {
				update_instance ();
				if (validate_data ()) {
					if (old_horario == null) {
						try {
							var res = conn.db.exec ("
INSERT INTO horario
(id_asignatura, id_bloque, sala)
VALUES
(
'" + horario.asignatura.id_asignatura.to_string () + "',
'" + horario.bloque.id_bloque.to_string () + "',
'" + conn.escape (horario.sala) + "'
)
							");
							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_horario (); // Signal the parent to update itself
							this.close ();
						}
					}
					else {
						try {
							var res = conn.db.exec ("
UPDATE horario SET
	id_asignatura = " + horario.asignatura.id_asignatura.to_string () + ",
	id_bloque = " + horario.bloque.id_bloque.to_string () + ",
	sala = '" + conn.escape (horario.sala) + "'
WHERE id_asignatura = " + old_horario.asignatura.id_asignatura.to_string () + " AND
id_bloque = " + old_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
							}
						}
						catch (PostgresError e) {
							#if DEBUG
								error (e.message);
							#else
								warning (e.message);
							#endif
						}
						finally {
							save_horario (); // Signal the parent to update itself
							this.close ();
						}
					}
				}
			}
		}

		private bool validate_data () {
			if (horario.sala.strip () == "") {
				var msg = new Gtk.MessageDialog (this,
					Gtk.DialogFlags.MODAL,
					Gtk.MessageType.ERROR,
					Gtk.ButtonsType.CLOSE,
					"Error: No se puede dejar la sala en blanco!");
				msg.response.connect ((response_id) => {
					msg.destroy ();
				});
				msg.set_title ("Error");
				msg.run ();
				return false;
			}
			var res = conn.db.exec ("
SELECT id_asignatura, id_bloque
FROM horario
			");
			if (res.get_status () != ExecStatus.TUPLES_OK) {
				#if DEBUG
					error (conn.db.get_error_message ());
				#else
					warning (conn.db.get_error_message ());
					return false;
				#endif
			}
			else {
				var wra = new ResultWrapper (res);
				int n = res.get_n_tuples ();
				for (int i = 0; i < n; i++) {
					try {
						if (check_old_horario (wra, i) &&
								wra.get_int_n (i, "id_asignatura") == horario.asignatura.id_asignatura &&
								wra.get_int_n (i, "id_bloque") == horario.bloque.id_bloque) {
							var msg = new Gtk.MessageDialog (this,
								Gtk.DialogFlags.MODAL,
								Gtk.MessageType.ERROR,
								Gtk.ButtonsType.CLOSE,
								"Error: Un horario con la asignatura \"%s\" y bloque \"%s\" ya existe!",
								horario.asignatura.nombre, horario.bloque.descripcion);
							msg.response.connect ((response_id) => {
								msg.destroy ();
							});
							msg.set_title ("Error");
							msg.run ();
							return false;
						}
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
				}
			}
			return true;
		}

		private bool check_old_horario (ResultWrapper wra, int i) {
			try {
				if (old_horario == null) {
					// This is a new horario
					return true;
				}
				else if (old_horario.asignatura.id_asignatura != wra.get_int_n (i, "id_asignatura") ||
						old_horario.bloque.id_bloque != wra.get_int_n (i, "id_bloque")) {
					return true;
				}
				else {
					return false;
				}
			}
			catch (Error e) {
				#if DEBUG
					error (e.message);
				#else
					warning (e.message);
					return false;
				#endif
			}
		}

		private void update_instance () {
			horario.sala = sala.get_text ().strip ();

			Asignatura new_asignatura = new Asignatura ();
			Gtk.TreeIter iter;
			asignatura.get_active_iter (out iter);
			if (asignatura_list_store.iter_is_valid (iter)) {
				asignatura_list_store.get (iter,
					AsignaturaColumn.ASIGNATURA, out new_asignatura);
			}
			horario.asignatura = new_asignatura;

			Bloque new_bloque = new Bloque ();
			bloque.get_active_iter (out iter);
			if (bloque_list_store.iter_is_valid (iter)) {
				bloque_list_store.get (iter,
					BloqueColumn.BLOQUE, out new_bloque);
			}
			horario.bloque = new_bloque;
		}

		public void initialize () {
			var res = conn.db.exec ("
SELECT id_asignatura, nombre
FROM 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);
				asignaturas = 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")
						);
						asignaturas.append (result);
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
				}
			}

			res = conn.db.exec ("
SELECT id_bloque, descripcion
FROM 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);
				bloques = new List<Bloque> ();
				int n = res.get_n_tuples ();
				for (int i = 0; i < n; i++) {
					try {
						var result = new Bloque (
							wra.get_int_n (i, "id_bloque"),
							wra.get_string_n (i, "descripcion")
						);
						bloques.append (result);
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
				}
			}

			asignaturas.sort_with_data ((a, b) => {
				return strcmp (a.nombre, b.nombre);
			});

			bloques.sort_with_data ((a, b) => {
				return strcmp (a.descripcion, b.descripcion);
			});

			asignatura_list_store = new Gtk.ListStore (AsignaturaColumn.N_COLUMNS,
				typeof (string),
				typeof (Asignatura));

			bloque_list_store = new Gtk.ListStore (BloqueColumn.N_COLUMNS,
				typeof (string),
				typeof (Bloque));

			asignatura.set_model (asignatura_list_store);

			bloque.set_model (bloque_list_store);

			if (horario != null) {
				sala.set_text (horario.sala);
			}
			else {
				horario = new Horario ();
				horario.asignatura = new Asignatura ();
				horario.bloque = new Bloque ();
			}

			asignaturas.foreach ((entry) => {
				Gtk.TreeIter iter;
				asignatura_list_store.append (out iter);
				asignatura_list_store.set (iter,
					AsignaturaColumn.NAME, entry.nombre,
					AsignaturaColumn.ASIGNATURA, entry);
				if (entry.id_asignatura == horario.asignatura.id_asignatura) {
					asignatura.set_active_iter (iter);
				}
			});

			bloques.foreach ((entry) => {
				Gtk.TreeIter iter;
				bloque_list_store.append (out iter);
				bloque_list_store.set (iter,
					BloqueColumn.DESCRIPCION, entry.descripcion,
					BloqueColumn.BLOQUE, entry);
				if (entry.id_bloque == horario.bloque.id_bloque) {
					bloque.set_active_iter (iter);
				}
			});

			if (horario.asignatura.id_asignatura == 0 && horario.bloque.id_bloque == 0) {
				asignatura.set_active (0);
				bloque.set_active (0);
			}
		}
	}
}
