DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`roadmap_beforeInsert`
	BEFORE INSERT ON `roadmap`
	FOR EACH ROW
BEGIN
	SET NEW.editorFk = account.myUser_getId();

	IF NEW.name IS NOT NULL THEN
		SET NEW.name = UCASE(NEW.name);
	END IF;

	IF NEW.etd > NEW.eta AND NEW.etd IS NOT NULL AND NEW.eta IS NOT NULL THEN
		CALL util.throw('Departure time can not be after arrival time');
	END IF;

	IF NEW.trailerPlate IS NOT NULL THEN
		SET NEW.m3 = (SELECT m3 FROM vehicle WHERE numberPlate = NEW.trailerPlate);
	END IF;

	IF NEW.tugPlate IS NOT NULL THEN
		SET NEW.m3 = NEW.m3 + (SELECT m3 FROM vehicle WHERE numberPlate = NEW.tugPlate);
	END IF;

	IF NEW.driver1Fk IS NOT NULL THEN
		SET NEW.driverName = (SELECT CONCAT(w.firstName, ' ', w.lastName)
								FROM worker w
								WHERE w.id = NEW.driver1Fk);

		SET NEW.phone = (SELECT COALESCE(w.phone, c.mobile, c.phone, c.mobile)
							FROM worker w
								LEFT JOIN client c ON c.id = w.id
							WHERE w.id = NEW.driver1Fk);
	END IF;
END$$
DELIMITER ;