/* UPDATE EXISTING MED BUDDY */
/* =============================================================================================================== */
DROP PROCEDURE IF EXISTS updateMedBuddy;
COMMIT;

DELIMITER //

CREATE PROCEDURE `updateMedBuddy`(`p_id` VARCHAR(36), `p_name` VARCHAR(100), `p_shareMeds` TINYINT)
BEGIN

DECLARE errno INT;
DECLARE iBuddyCount INT;

DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
  GET CURRENT DIAGNOSTICS CONDITION 1 errno = MYSQL_ERRNO;
  SELECT errno AS MYSQL_ERROR;

  ROLLBACK;

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

  RESIGNAL;
END;

START TRANSACTION;

  SELECT COUNT(*)
  FROM `MedBuddies`
  WHERE `_id` = p_id
  AND `status` = 'active'
  INTO iBuddyCount;

  IF iBuddyCount = 0 THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'Cannot find Med Buddy to update';
  END IF;

  IF p_name IS NOT NULL THEN 
    UPDATE `MedBuddies`
    SET `name` = p_name,
      `updatedAt` = NOW()
    WHERE `_id` = p_id;
  END IF;

  IF p_shareMeds IS NOT NULL THEN 
    UPDATE `MedBuddies`
    SET `shareMeds` = p_shareMeds,
      `updatedAt` = NOW()
    WHERE `_id` = p_id;
  END IF;

  SELECT `_id`, `name`, `email`, `shareMeds`, `status`
  FROM `MedBuddies`
  WHERE `_id` = p_id;

COMMIT WORK;

END
//

COMMIT //

DELIMITER ;
