/*
 * 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.editor.ui")]
	public class AsociadoEditor : Gtk.ApplicationWindow {
		private Connection conn;
		private Asociado asociado;
		private Asociado? old_asociado = null;

		private List<Asignatura> asignaturas;
		private Gtk.ListStore asignatura_list_store;
		private List<Curso> cursos;
		private Gtk.ListStore curso_list_store;

		public signal void save_asociado ();

		private enum AsignaturaColumn {
			NAME,
			ASIGNATURA,
			N_COLUMNS
		}
		private enum CursoColumn {
			NAME,
			CURSO,
			N_COLUMNS
		}

		[GtkChild]
		private Gtk.ComboBoxText asignatura;

		[GtkChild]
		private Gtk.ComboBoxText curso;

		[GtkChild]
		private Gtk.Button save;

		[GtkChild]
		private Gtk.Button cancel;

		public AsociadoEditor (Gtk.Application application, Connection conn, Asociado? asociado) {
			Object (application: application);
			this.conn = conn;
			this.asociado = asociado;
			if (this.asociado != null) {
				this.old_asociado = new Asociado ();
				this.old_asociado.copy (asociado);
			}
		}

		[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_asociado == null) {
						try {
							var res = conn.db.exec ("
INSERT INTO asociado
(id_asignatura, id_curso)
VALUES
(
'" + asociado.asignatura.id_asignatura.to_string () + "',
'" + conn.escape (asociado.curso.id_curso) + "'
)
							");
							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_asociado (); // Signal the parent to update itself
							this.close ();
						}
					}
					else {
						try {
							var res = conn.db.exec ("
UPDATE asociado SET
	id_asignatura = " + asociado.asignatura.id_asignatura.to_string () + ",
	id_curso = '" + conn.escape (asociado.curso.id_curso) + "'
WHERE id_asignatura = " + old_asociado.asignatura.id_asignatura.to_string () + " AND
id_curso = '" + conn.escape (old_asociado.curso.id_curso) + "'"
							);
							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_asociado (); // Signal the parent to update itself
							this.close ();
						}
					}
				}
			}
		}

		private bool validate_data () {
			var res = conn.db.exec ("
SELECT id_asignatura, id_curso
FROM asociado
			");
			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_asociado (wra, i) &&
								wra.get_int_n (i, "id_asignatura") == asociado.asignatura.id_asignatura &&
								wra.get_string_n (i, "id_curso") == asociado.curso.id_curso) {
							var msg = new Gtk.MessageDialog (this,
								Gtk.DialogFlags.MODAL,
								Gtk.MessageType.ERROR,
								Gtk.ButtonsType.CLOSE,
								"Error: Un curso \"%s\" con la asignatura \"%s\" ya existe!",
								asociado.curso.nombre, asociado.asignatura.nombre);
							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_asociado (ResultWrapper wra, int i) {
			try {
				if (old_asociado == null) {
					// This is a new asociado
					return true;
				}
				else if (old_asociado.asignatura.id_asignatura != wra.get_int_n (i, "id_asignatura") ||
						old_asociado.curso.id_curso != wra.get_string_n (i, "id_curso")) {
					return true;
				}
				else {
					return false;
				}
			}
			catch (Error e) {
				#if DEBUG
					error (e.message);
				#else
					warning (e.message);
					return false;
				#endif
			}
		}

		private void update_instance () {
			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);
			}
			asociado.asignatura = new_asignatura;

			Curso new_curso = new Curso ();
			curso.get_active_iter (out iter);
			if (curso_list_store.iter_is_valid (iter)) {
				curso_list_store.get (iter,
					CursoColumn.CURSO, out new_curso);
			}
			asociado.curso = new_curso;
		}

		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_curso, nombre
FROM curso
			");
			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);
				cursos = new List<Curso> ();
				int n = res.get_n_tuples ();
				for (int i = 0; i < n; i++) {
					try {
						var result = new Curso (
							wra.get_string_n (i, "id_curso"),
							wra.get_string_n (i, "nombre")
						);
						cursos.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);
			});

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

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

			curso_list_store = new Gtk.ListStore (CursoColumn.N_COLUMNS,
				typeof (string),
				typeof (Curso));

			asignatura.set_model (asignatura_list_store);

			curso.set_model (curso_list_store);

			if (asociado == null) {
				asociado = new Asociado ();
				asociado.asignatura = new Asignatura ();
				asociado.curso = new Curso ();
			}

			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 == asociado.asignatura.id_asignatura) {
					asignatura.set_active_iter (iter);
				}
			});

			cursos.foreach ((entry) => {
				Gtk.TreeIter iter;
				curso_list_store.append (out iter);
				curso_list_store.set (iter,
					CursoColumn.NAME, entry.id_curso,
					CursoColumn.CURSO, entry);
				if (entry.id_curso == asociado.curso.id_curso) {
					curso.set_active_iter (iter);
				}
			});

			if (asociado.asignatura.id_asignatura == 0 && asociado.curso.id_curso.strip () == "") {
				asignatura.set_active (0);
				curso.set_active (0);
			}
		}
	}
}
