/* SYNC BLOOD PRESSURE */
/* =============================================================================================================== */
DROP PROCEDURE IF EXISTS updateBloodPressures;
COMMIT;

DELIMITER //

CREATE PROCEDURE `updateBloodPressures`(`p_transaction` VARCHAR(36), `p_userId` BIGINT, `p_bloodPressureCount` INT, 
  `p_date` DATETIME)

BEGIN

DECLARE errno INT;
DECLARE iBloodPressureCount 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: uBloodPres', now(), errno; 

  RESIGNAL;
END;

START TRANSACTION;

SELECT COUNT(`remoteId`)
FROM `TempBloodPressures`
WHERE `transaction` = p_transaction
INTO iBloodPressureCount;

IF iBloodPressureCount <> p_bloodPressureCount THEN
  SIGNAL SQLSTATE '45000'
  SET MESSAGE_TEXT = 'Temp blood pressure count does not match provided blood pressure count.';
END IF;

IF p_bloodPressureCount IS NOT NULL AND p_bloodPressureCount > 0 THEN
  INSERT INTO `BloodPressures`(`remoteId`, `userId`, `dependant`, `day`, `systolic`, `diastolic`, `unit`, `status`, 
    `updatedAt`, `createdAt`)
  SELECT `temp`.`remoteId`, `temp`.`userId`, `temp`.`dependant`, `temp`.`day`, `temp`.`systolic`, `diastolic`, 
    `temp`.`unit`, `temp`.`status`, `temp`.`updatedAt`, `temp`.`createdAt`
  FROM `TempBloodPressures` `temp`
  WHERE `temp`.`transaction` = p_transaction
  ON DUPLICATE KEY
  UPDATE `day` = `temp`.`day`,
    `systolic` = `temp`.`systolic`,
    `diastolic` = `temp`.`diastolic`,
    `unit` = `temp`.`unit`,
    `status` = `temp`.`status`,
    `updatedAt` = `temp`.`updatedAt`;

  DELETE FROM `TempBloodPressures`
  WHERE `transaction` = p_transaction;
END IF;

SELECT *
FROM `BloodPressures`
WHERE `userId` = p_userId
AND `status` NOT IN ('inactive', 'deleted')
AND `day` > p_date;

COMMIT WORK;

END
//

COMMIT //

DELIMITER ;
