Source: util/updateExercise.js

const query = require("./query.js");

/**
 * Creates or updates an exercise given the required information
 * @param {string} req.query.sheetMusicId The sheet music ID to be accessed.
 * @param {number} req.query.trackNumber The track number to be accessed
 * @param {number} req.query.staffNumber The staff number to be accessed
 * @param {number} req.query.measureStart The start measure number for the exercise
 * @param {number} req.query.measureEnd The end measure number for the exercise
 * @param {boolean} req.query.isDurationExercise Whether the exercise should be a duration exercise or not
 * @returns {string} If successful, the ID of the exercise generated or accessed. Otherwise, if an error occurs then null
 */
const updateExerciseTable = async (sheetMusicId, trackNumber, staffNumber, measureStart, measureEnd, isDurationExercise) => {   
    try {
        const obj_1 = await query("SELECT hex(exercise_id) AS exercise_id, num_users FROM tma.exercise WHERE sheet_music_id=unhex(?) AND track_number=? AND staff_number=? AND measure_start=? AND measure_end=? AND is_duration_exercise=?", [sheetMusicId, trackNumber, staffNumber, measureStart, measureEnd, isDurationExercise]);
        if (obj_1.results.length === 0) {
            const obj_2 = await query("SELECT replace(uuid(),'-','') AS uuid");
            const exerciseId = obj_2.results[0]["uuid"];
            await query("INSERT INTO tma.exercise (exercise_id, sheet_music_id, track_number, staff_number, measure_start, measure_end, is_duration_exercise, num_users) values(unhex(?), unhex(?), ?, ?, ?, ?, ?, 1)", [exerciseId, sheetMusicId, trackNumber, staffNumber, measureStart, measureEnd, isDurationExercise]);
            return exerciseId;
        } else {
            let exerciseId = obj_1.results[0]["exercise_id"];
            let newNumUsers = obj_1.results[0]["num_users"] + 1;
            await query("UPDATE tma.exercise SET num_users=? WHERE exercise_id=unhex(?)", [newNumUsers, exerciseId]);
            return exerciseId;
        }
    } catch(error) {
        return null;
    }
}

module.exports = updateExerciseTable;