#!/bin/bash

export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
USER=${USER:-$(whoami)}

FILE=/home/$USER/.4yousee/player/4YouSeeChromeApp/scripts/WebServer/API/PlayerApi.js
CHANGED=0

MMPLAY_FUNC=$(cat <<-END
PlayerApi.prototype.mmplay = function (params, callback) {
    switch (this.method) {
        case 'POST':
            if (this.body && this.body.hasOwnProperty('timeSync')) {
                const receivedTime = new Date(this.body.timeSync * 1000);
                let seconds = receivedTime.getSeconds();
                let milliseconds = receivedTime.getMilliseconds();
                let waitTimeInSeconds = (seconds >= 30) ? (60 - seconds) : (30 - seconds);
                let waitTime = (waitTimeInSeconds * 1000) - milliseconds;
                if (waitTime <= 0) {
                    waitTime += 30000;
                }
                setTimeout(() => {
                    this.postPlay(params, callback);
                }, waitTime);
            } else {
                callback('E0400', { message: 'timeSync parameter is required in the request body.' });
            }
            break;
        default:
            callback('E0404', { message: 'Not found.' });
            break;
    }
};
END
)

if ! grep -q "PlayerApi.prototype.mmplay =" "$FILE"; then
    awk -v mmplay="$MMPLAY_FUNC" '/PlayerApi.prototype.play = function \(params, callback\) {/ {print mmplay "\n" $0; next} 1' "$FILE" > temp.js && mv temp.js "$FILE"
    echo "mmplay function added before play."
    CHANGED=1
else
    echo "mmplay function already exists."
fi

if ! grep -q "'mmplay'," "$FILE"; then
    echo "Ensuring mmplay is listed in listFunctions..."
    awk '/var listFunctions = \[/{print;print "    '\''mmplay'\'',";next}1' "$FILE" > temp.js && mv temp.js "$FILE"
    CHANGED=1
fi

if [[ $CHANGED -eq 1 ]]; then
    echo "Changes were made to the file, performing specified actions..."
    pkill -f 4you
    systemctl --user restart 4youseeRobot.service
else
    echo "No changes were made."
fi

echo "Done."
