DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`routeProposal_`(vTicketFk INT)
	RETURNS int(11)
	NOT DETERMINISTIC
	READS SQL DATA
BEGIN

	DECLARE vRouteFk INT;
    DECLARE vAddressFk INT;
    DECLARE vShipped DATETIME;
    
    SELECT addressFk, date(shipped) INTO vAddressFk, vShipped
		FROM vn.ticket 
        WHERE id = vTicketFk;

	SELECT routeFk INTO vRouteFk
		FROM
			(SELECT t.routeFk, sum(af.friendship) friendshipSum
				FROM vn.ticket t
					JOIN cache.addressFriendship af ON af.addressFk2 = t.addressFk AND af.addressFk1 = vAddressFk
				WHERE t.shipped BETWEEN vShipped and MIDNIGHT(vShipped)
					AND t.routeFk
				GROUP BY routeFk
				ORDER BY friendshipSum DESC
        ) sub
        LIMIT 1;
	
	RETURN vRouteFk;
END$$
DELIMITER ;
