/* SAVE TRACKER ANSWER */
/* =============================================================================================================== */
DROP PROCEDURE IF EXISTS saveTrackerAnswer;
COMMIT;

DELIMITER //

CREATE PROCEDURE `saveTrackerAnswer`(`p_userId` VARCHAR(36), `p_trackerId` INT, `p_optionId` INT)

BEGIN

DECLARE errno INT;

DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
  GET CURRENT DIAGNOSTICS CONDITION 1 errno = MYSQL_ERRNO;
  ROLLBACK;

	INSERT INTO debug_log(activity, ts_when, log) 
  SELECT 'PROC ERR:sTrackAnswr', now(), errno; 

  RESIGNAL;
END;

START TRANSACTION;

  INSERT IGNORE INTO `TrackerAnswers`(`userId`, `trackerId`, `trackerQuestion`, `optionId`, `trackerOption`, 
    `timestamp`, `createdAt`, `updatedAt`)
  SELECT p_userId, p_trackerId, `T`.`question`, p_optionId, `O`.`optionWording`, NOW(), NOW(), NOW()
  FROM `TrackerOptions` AS `O`
  LEFT JOIN `Trackers` AS `T` ON `O`.`trackerId` = `T`.`_id`
  WHERE `O`.`_id` = p_optionId;

  SELECT `_id`, `optionId`, `trackerId`, DATE_FORMAT(timestamp, '%Y-%m-%dT%H:%i:%s.000Z') AS timestamp, 
    1 AS `synced`
  FROM `TrackerAnswers`
  WHERE `userId` = p_userId
  AND `trackerId` = p_trackerId
  AND `optionId` = p_optionId
  AND TIMESTAMPDIFF(SECOND, `timestamp`, NOW()) < 60
  AND TIMESTAMPDIFF(SECOND, `timestamp`, NOW()) > -60
  ORDER BY `timestamp` DESC
  LIMIT 1;

COMMIT WORK;

END
//

COMMIT //

DELIMITER ;
