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

		private List<Profesor> profesores;

		private Gtk.ListStore profesor_list_store;
		public signal void save_asignatura ();

		private enum ProfesorColumn {
			PROFESOR_NAME,
			PROFESOR,
			N_COLUMNS
		}

		[GtkChild]
		private Gtk.Entry asignatura_name;

		[GtkChild]
		private Gtk.ComboBoxText profesor;

		[GtkChild]
		private Gtk.Button save;

		[GtkChild]
		private Gtk.Button cancel;

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

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

		private bool validate_data () {
			if (asignatura.nombre.strip () == "") {
				var msg = new Gtk.MessageDialog (this,
					Gtk.DialogFlags.MODAL,
					Gtk.MessageType.ERROR,
					Gtk.ButtonsType.CLOSE,
					"Error: No se puede dejar el nombre de la asignatura 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, nombre, rut_profesor
FROM asignatura
			");
			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 (wra.get_int_n (i, "id_asignatura") != asignatura.id_asignatura &&
							wra.get_string_n (i, "nombre").down () == asignatura.nombre.down () &&
								wra.get_string_n (i, "rut_profesor") == asignatura.profesor.rut_profesor) {
							var msg = new Gtk.MessageDialog (this,
								Gtk.DialogFlags.MODAL,
								Gtk.MessageType.ERROR,
								Gtk.ButtonsType.CLOSE,
								"Error: Una asignatura \"%s\" con el profesor \"%s\" ya existe!",
								asignatura.nombre, asignatura.profesor.nombres + " " + asignatura.profesor.apellidos);
							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 void update_instance () {
			asignatura.nombre = asignatura_name.get_text ().strip ();
			Profesor new_profesor = new Profesor ();
			Gtk.TreeIter iter;
			profesor.get_active_iter (out iter);
			if (profesor_list_store.iter_is_valid (iter)) {
				profesor_list_store.get (iter,
					ProfesorColumn.PROFESOR, out new_profesor);
			}
			asignatura.profesor = new_profesor;
		}

		public void initialize () {
			var res = conn.db.exec ("
SELECT rut_profesor, nombres, apellidos
FROM profesor
			");
			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);
				profesores = new List<Profesor> ();
				int n = res.get_n_tuples ();
				for (int i = 0; i < n; i++) {
					try {
						var result = new Profesor (
							wra.get_string_n (i, "rut_profesor"),
							wra.get_string_n (i, "nombres"),
							wra.get_string_n (i, "apellidos")
						);
						profesores.append (result);
					}
					catch (Error e) {
						#if DEBUG
							error (e.message);
						#else
							warning (e.message);
						#endif
					}
				}
			}

			profesores.sort_with_data ((a, b) => {
				return strcmp (a.nombres, b.nombres);
			});

			profesor_list_store = new Gtk.ListStore (ProfesorColumn.N_COLUMNS,
				typeof (string),
				typeof (Profesor));

			profesor.set_model (profesor_list_store);

			if (asignatura != null) {
				asignatura_name.set_text (asignatura.nombre);
			}
			else {
				asignatura = new Asignatura ();
				asignatura.profesor = new Profesor ();
			}

			profesores.foreach ((entry) => {
				Gtk.TreeIter iter;
				profesor_list_store.append (out iter);
				profesor_list_store.set (iter,
					ProfesorColumn.PROFESOR_NAME, entry.nombres + " " + entry.apellidos,
					ProfesorColumn.PROFESOR, entry);
				if (entry.rut_profesor == asignatura.profesor.rut_profesor) {
					profesor.set_active_iter (iter);
				}
			});

			if (asignatura.id_asignatura == 0) {
				profesor.set_active (0);
			}
		}
	}
}
