/*
 * 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.alumno.edit.ui")]
	public class RegistroAlumnoEdit : Gtk.ApplicationWindow {
		private Connection conn;
		private Registro registro;

		public signal void save_nota ();

		[GtkChild]
		private Gtk.Entry nota;

		[GtkChild]
		private Gtk.Button save;

		[GtkChild]
		private Gtk.Button cancel;

		public RegistroAlumnoEdit (Gtk.Application application, Connection conn, Registro registro) {
			Object (application: application);
			this.conn = conn;
			this.registro = registro;
		}

		[GtkCallback]
		public void on_clicked_button (Gtk.Button button) {
			if (button == cancel) {
				this.close ();
			}
			else if (button == save) {
				update_instance ();
				if (validate_data ()) {
					try {
						var res = conn.db.exec ("
UPDATE registro SET
	nota = '" + registro.nota.to_string () + "'
WHERE id_asignatura = " + registro.asignatura.id_asignatura.to_string () + " AND
rut_alumno = '" + conn.escape (registro.alumno.rut_alumno) + "'"
						);
						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_nota (); // Signal the parent to update itself
						this.close ();
					}
				}
			}
		}

		private bool validate_data () {
			if (registro.nota < 1) {
				var msg = new Gtk.MessageDialog (this,
					Gtk.DialogFlags.MODAL,
					Gtk.MessageType.ERROR,
					Gtk.ButtonsType.CLOSE,
					"Error: La nota no puede ser menor a 1!");
				msg.response.connect ((response_id) => {
					msg.destroy ();
				});
				msg.set_title ("Error");
				msg.run ();
				return false;
			}
			if (registro.nota > 7) {
				var msg = new Gtk.MessageDialog (this,
					Gtk.DialogFlags.MODAL,
					Gtk.MessageType.ERROR,
					Gtk.ButtonsType.CLOSE,
					"Error: La nota no puede ser mayor a 7!");
				msg.response.connect ((response_id) => {
					msg.destroy ();
				});
				msg.set_title ("Error");
				msg.run ();
				return false;
			}
			return true;
		}

		private void update_instance () {
			registro.nota = float.parse (nota.get_text ().strip ());
		}

		public void initialize () {
			nota.set_text (registro.nota.to_string ("%.1f"));
		}
	}
}
