
// Universal puzzle functions
// TODO: These probably can be moved to the index.html script

const isExpired = (expiration) => {
    let date = new Date();
    let seconds = Math.round(date.getTime() / 1000);
    return seconds > expiration;
};

const newExpiration = (additionalSeconds) => {
    let date = new Date();
    let seconds = Math.round(date.getTime() / 1000);
    return seconds + additionalSeconds;
};

// This function sends the player's data to the server and then retrieves
// the data the other players synced as well.
const syncPuzzleData = (data_name, data_value) => {
    ws.send(JSON.stringify({
        "message": "Sync me, please!",
        "game": game,
        "puzzle": data_name,
        "UUID": UUID,
        "data": data_value
    }));
    console.log("syncing");
    return combineDataSync(data_name, data_value);
};

// This loads the reward assets when a player wins a puzzle
const loadTheWin = () => {
    //TODO: actually write this
    gameApp.innerHTML = puzzles[currentPuzzle["puzzle"]]["solution"];
    ws.send(JSON.stringify({
        "message": "Winner, winner, chicken dinner!",
        "game": game
    }));
    if (currentPuzzle["puzzle"] == "locked-door") {
        const smash = new Audio("./assets/smash.mp3");
        smash.play();
    }
};

const removeCrack = (area) => {
    document.getElementById(area).classList.remove("cracked");
};

const pauseHitting = () => {
    hittingSound.pause();  
};

const hittingSound = new Audio("./assets/hitting.mp3");

// This is run when a player "hits" (clicks) any area of the door.
// The area responds to one of the keys in data_locked_door["values"].
const run_locked_door = (area) => {
    console.log("run_locked_door: check of data_locked_door");
    console.log(data_locked_door);
    console.log("checking corrected_data_locked_door");
    console.log(corrected_data_locked_door);
    document.getElementById(area).classList.add("cracked");
    hittingSound.play();
    setTimeout(removeCrack, 500, area);
    if (isExpired(data_locked_door[UUID]["expiration"])) {
        console.log("it's expired!");
        data_locked_door = build_door_data();
        corrected_data_locked_door[UUID] = build_door_data()[UUID];
    }
    // Add 1 to the area's "hit" points
    data_locked_door[UUID]["values"][area]++;
    // Add 1 to the corrected data as well before we check for
    // the winning condition.
    corrected_data_locked_door[UUID]["values"][area]++;
    // Check all areas of the corrected door values
    for (const [ key, value ] of Object.entries(corrected_data_locked_door[UUID]["values"])) {
        // If any value is less than or equal to 9, sync the data and exit.
        // The player didn't win this hit.
        if (value <= 9) {
            corrected_data_locked_door = syncPuzzleData("data_locked_door", data_locked_door);
            return;
        }
    }
    // If we get here, all values should have been above 9,
    // and the player won!
    loadTheWin("locked_door");
};

// safe
// TODO: Put the next puzzle's run event here

// The door has 5 areas to track the number of hits
// When all parts of the door have over 9 hits, the door breaks
// The UUID is so we can track which players have made what progress
// and combine their work without duplicating it.

const build_door_data = () => {
  let expiration = newExpiration(120);
  return {
    [UUID]: {
        "expiration": expiration,
        "values": {
            "area_1": 0,
            "area_2": 0,
            "area_3": 0,
            "area_4": 0,
            "area_5": 0,
            "area_6": 0
        }
    }
};
};

let data_locked_door = build_door_data();

console.log("first check of data_locked_door");
console.log(data_locked_door);

// Set the corrected data to the player's data to start.
// Later this will be a combination of all players' data synced.
// This is the object we want to check for the winning condition.
let corrected_data_locked_door = build_door_data();

// We sync data here for any puzzles that require multiple players
// to work together
const combineDataSync = (data_name) => {
    if (data_name == "data_locked_door") {
        let new_locked_door_data = build_door_data();
        // We want to check the value of each area of the door
        for (const [ key, value ] of Object.entries(data_locked_door[UUID]["values"])) {
            // We want to check each synced dictionary. Each one should be from
            // another player with a UUID.
            for (const [ sync_key, sync_value ] of Object.entries(synced_data_value)) {
                // We check to make sure the UUID of the data isn't our own.
                // If it is, we skip it.
                if (sync_key != UUID) {
                    // We add the values together.
                    // I.e. if player #1 hit area_1 4 times,
                    // and player #2 hit area_1 6 times,
                    // area_1 has 10 hits total
                    new_locked_door_data[UUID]["values"][key] = data_locked_door[UUID]["values"][key] + synced_data_value[sync_key]["values"][key];
                }
            }
        }
        // We returned the synced, combined data
        return new_locked_door_data;
    }
};