
// This loads the reward assets when a player wins a puzzle
const loadTheWin = () => {
    gameApp.innerHTML = puzzles[currentPuzzle["puzzle"]]["solution"];
    ws.send(JSON.stringify({
        "message": "Winner, winner, chicken dinner!",
        "game": game,
        "puzzle": currentPuzzle["puzzle"]
    }));
    if (currentPuzzle["puzzle"] == "locked-door") {
        const smash = new Audio("./assets/smash.mp3");
        smash.play();
    }
    if (currentPuzzle["puzzle"] == "safe") {
        const safe = new Audio("./assets/safe-opening.mp3");
        safe.play();
    }
    if (currentPuzzle["puzzle"] == "sams-phone") {
        const phone = new Audio("./assets/phone-unlocked.mp3");
        phone.play();
    }
    if (currentPuzzle["puzzle"] == "laptop") {
        const laptop = new Audio("./assets/laptopsuccess.mp3");
        laptop.play();
    }
    if (currentPuzzle["puzzle"] == "elevator") {
        const elevator = new Audio("./assets/elevatorsuccess.mp3");
        elevator.play();
    }
    if (currentPuzzle["puzzle"] == "basement") {
        const basement = new Audio("./assets/basementsolved.mp3");
        basement.play();
    }
};

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

const isIdenticalList = (list1, list2) => {
    try {
        if (list1.length !== list2.length) {
            return false;
        }
        for (let i=0; i < list1.length; i++) {
          if (list1[i] === list2[i]) {
              continue;
          }   
          else {
              return false;
          }
        }
        return true;
    }
    catch (e) {
        console.log(e);
        return false;
    }
};

let elevator_presses = [];
const elevator_answer = [1, 1, 0, 9, 1];

const elevatorButtons = (button) => {
  clickSound.play();
  if (elevator_presses.length > 4) {
      if (isIdenticalList(elevator_answer, elevator_presses)) {
          loadTheWin();
          return;
      }
      elevator_presses = [];
      document.getElementById("screen").innerHTML = "INCORRECT";
      return;
  }
  if (elevator_presses.length < 5) {
      elevator_presses.push(button);
      if (isIdenticalList(elevator_answer, elevator_presses)) {
        loadTheWin();
        return;
      }
      let numString = "";
      for (let i=0;i < elevator_presses.length; i++) {
          numString += elevator_presses[i].toString();
      }
      document.getElementById("screen").innerHTML = numString;
  }
}

function startDrag(e) {
    // determine event object
    if (!e) {
        e = window.event;
    }
    if(e.preventDefault) e.preventDefault();

    // IE uses srcElement, others use target
    targ = e.target ? e.target : e.srcElement;

    if (targ.className != 'dragme') {return}
    // calculate event X, Y coordinates
        offsetX = e.clientX;
        offsetY = e.clientY;

    // assign default values for top and left properties
    if(!targ.style.left) { targ.style.left='0px'}
    if (!targ.style.top) { targ.style.top='0px'}

    // calculate integer values for top and left 
    // properties
    coordX = parseInt(targ.style.left);
    coordY = parseInt(targ.style.top);
    drag = true;

    // move div element
        document.onmousemove=dragDiv;
    return false;

}
function dragDiv(e) {
    if (!drag) {return}
    if (!e) { e= window.event}
    // move div element
    targ.style.left=coordX+e.clientX-offsetX+'px';
    targ.style.top=coordY+e.clientY-offsetY+'px';
    return false;
}
function stopDrag() {
    drag=false;
}

function mobileDrag(e) {
    const uvLight = document.getElementById("uv-light");
    // grab the location of touch

    var touchLocation = e.targetTouches[0];
    
    // assign box new coordinates based on the touch.
    uvLight.style.left = touchLocation.pageX + 'px';
    uvLight.style.top = touchLocation.pageY + 'px';
    drag=true;
}
  

function stopMobileDrag(e) {
    drag=false;
}

const basementAnswers = {
    "Why would you say such a naughty word in front of cute lil' Sir Isaac? That's not fucking nice.": ["fuck", "fucking", "damn", "damnit", "dammit", "shit", "bitch", "cunt", "bastard", "bitching", "crap", "bullshit", "shitton", "shitting", "fucked", "fucked up", "asshole", "ass", "dang", "dangit", "heck", "hell", "cocksucker", "piss"],
    "Eh, that seems like overkill": ["gun", "guns", "ak47", "ak-47", "assault", "fists", "knife", "ax", "glock", "grenade", "tnt", "explosives", "bullets", "pepper spray", "weapon", "weapons", "shotgun", "bat", "sword"],
    "We're supposed to be freeing Guardian Sam and Queen Tee-Tee, not getting kinky...": ["handcuffs", "rope", "zip-ties", "zip ties", "zipties", "dildo", "sex", "sex toys", "penis", "dick", "hookers", "prostitutes", "wang"],
    "That might make the basement more clean. I guess Guardian Sam and Queen Tee-Tee would appreciate that while staying in their jailcell...": ["vacuum", "vaccuum", "vacum", "duster", "spray", "spraybottle", "mop", "broom", "dustbin", "trashcan", "trash", "bags", "gloves", "rags", "papertowels", "paper towels", "towels", "cleaning supplies", "cleaner", "bleach", "pinesol", "soap", "bucket", "water"],
    "Some nice decor for their jailcell, how sweet. But they'd still rather get broken out I think.": ["lamp", "rug", "carpet", "floor", "flooring", "light", "chair", "couch", "table", "chairs", "painting", "wallhanging", "wall-hanging", "plant", "pot", "flowers", "roses", "candle", "candles", "basket", "tray"],
    "Is Sir Isaac helping you with these ideas? You can't go play and leave Guardian Sam and Queen Tee-Tee in there. ": ["ball", "ballpit", "jump-rope", "jump rope", "jumprope", "toy", "toys", "cat toy", "videogames", "videogame", "video", "basketball", "baseball", "cat food", "treats", "salami", "sausage", "food", "tacos", "burgers", "sushi", "sandwich", "sandwiches", "microphone", "nonsense", "newton's sword"],
    "That wouldn't be enough to break the jailcell open. We might have to work smarter.": ["hammer", "screwdriver", "chisel", "mallet", "tool", "tools", "crowbar", "prybar", "jackhammer", "jack-hammer", "drill", "saw", "buzzsaw", "pin", "nail", "hairpin", "hair pin", "hair-pin", "bobby pin", "bobby-pin", "bobbypin", "flashlight", "ladder", "stool", "step-stool", "stepstool", "shovel", "wire", "cord", "outlet", "extension cord", "tape", "duct-tape", "duck tape", "duck-tape", "duct tape"],
    "You're going to make the Game Master hungry, but food bribery won't help you.": ["dessert", "chocolate", "candy", "cookies", "cake", "doughnuts", "chocolate-chip", "chocolate chip cookies", "oreos", "chips"],
    "Maybe try a more specific item?": ["box", "boxes", "bin", "bottle", "bottles", "jar", "jars", "file", "files", "folder", "container", "something", "thing", "a thing", "shelves", "shelf", "a shelf"],
    "I'm afraid to ask if you're thinking of throwing them or what...": ["sam", "guardian sam", "jenna", "newton", "seraph", "phoenix", "the cat", "the dog", "gaia", "ricky", "fish", "scruffy", "queen tee-tee", "tee-tee", "game master", "the game master", "poop"],
    "You lost the game": ["the game"],
    "No, u": ["dumb", "stupid", "idiot"],
    "I like it. It won't help, but I like it.": ["you", "pokemon", "glitter", "glitterbomb", "paint", "lunch"],
    "Nah, Queen Tee-Tee's signet won't work here": ["signet", "tee-tee's paper", "queen tee-tee's paper", "paw print", "cat paw"],
    "That's obvious, but how do we find a specific one that unlocks the jailcell?": ["handprint", "fingerprint", "hand", "finger", "thumb", "thumbprint"],
    "Are you going to seduce the jailcell into opening up? That didn't even work on my last date.": ["bra", "bras", "pants", "underwear", "panties", "boobs", "breasts", "titties", "tits", "netflix", "date", "dinner", "chest", "naked", "nudity"],
    "I don't think the jailcell will be impressed with your tech.": ["phone", "laptop", "computer", "keyboard"],
    "That's the thing we need to open.": ["lock", "jailcell", "jail", "prison", "cell", "jail-cell", "finger-scanner", "fingerprint-scanner", "finger scanner", "finger-print scanner"],
    "That won't help get the jailcell open": ["vent", "heater", "pipe", "door", "bars"],
    "As Professor Oak always said, it's not time to use that.": ["bike", "bicycle", "motorcycle", "car", "vehicle", "truck", "van", "bulldozer"],
    "win": ["uv", "uv light", "uv-light", "blacklight", "black light", "black-light", "uv wand", "uv flashlight", "uv lamp", "blacklight lamp", "ultra-violet", "ultraviolet", "ultra violet", "ultra-violet light", "ultraviolet light", "ultra violet light", "ultra-violet lamp", "ultraviolet lamp", "ultra violet lamp"],
};

const tryBasement = () => {
    let userInput = document.getElementById('basement-input').value.toLowerCase();
    
    for (const [type, valueList] of Object.entries(basementAnswers)) {
        for (let i=0; i < valueList.length; i++) {
            if (valueList[i] === userInput) {
                console.log("something matched");
                if (type === "win") {
                    // Load the moveable light
                    const uvLight = document.getElementById("uv-light");
                    uvLight.classList.remove("invisible");
                     document.getElementById("basement-response").innerHTML = "That's a great item! Let's use it to look around!";
                    document.getElementById('basement-wrapper').classList.add("invisible");
                    uvLight.onmousedown = startDrag;
                    uvLight.onmouseup = stopDrag;
                    uvLight.addEventListener('touchmove', function (e) {
                        // grab the location of touch
                        var touchLocation = e.targetTouches[0];
    
                        // assign box new coordinates based on the touch.
                        uvLight.style.left = touchLocation.pageX + 'px';
                        uvLight.style.top = touchLocation.pageY + 'px';
                        
                        if ( (touchLocation.pageX > 100) && (touchLocation.pageX < 150) && (touchLocation.pageY > 150) && (touchLocation.pageY < 200)) {
                            loadTheWin();
                        }
                        drag=true;
                        });
                    uvLight.addEventListener('touchend', function(e) {
                        drag=false;
                        
                    });
                }
                else {
                    document.getElementById("basement-response").innerHTML = type;
                    document.getElementById('basement-input').value = "";
                }
            return;
            }
        }
    }
    const randomResponses = ["Uhhh, no.", "We can't use that.", "Try something else.", "Sorry, that won't work."];

    console.log("nothing matched");
    // Nothing matched, so send a generic response
    const randomResponse = randomResponses[Math.floor(Math.random() * randomResponses.length)];
    console.log(randomResponse);
    document.getElementById("basement-response").innerHTML = randomResponse;
    document.getElementById('basement-input').value = "";
};

// Laptop clues
// Oct: TiMp1023)
// Nov: TiMp1123!

// Jan: TiMp0124!

// Feb: TiMp0224@  <--- Players are in Feb

const laptop_password = "TiMp0224@";

const tryLaptop = () => {
    if (document.getElementById('laptop-input').value === laptop_password) {
        loadTheWin();
    }
    else {
        document.getElementById('laptop-input').value = "";
        const laptopFail = new Audio("./assets/laptopfail.mp3");
        laptopFail.play();
    }
};

// up, up, down, down, left, right, left, right
const sam_answer = [2,2,8,8,4,6,4,6];
let phone_presses = [];

const unpressDot = (dot_id) => {
    const dotElement = document.getElementById(dot_id);
    if (dotElement) {
        dotElement.classList.remove("small-dot");
    }
};

const unpressReset = () => {
  document.getElementById("phone-reset").classList.remove("small-text");  
};

const resetPhone = () => {
  tapSound.play();
  phone_presses = [];
  document.getElementById("phone-reset").classList.add("small-text");
  setTimeout(unpressReset, 250);
};

const samsPhone = (dot) => {
    document.getElementById("dot-" + dot).classList.add("small-dot");
    tapSound.play();
    setTimeout(unpressDot, 250, "dot-" + dot);
    if (phone_presses.length > 7) {
      if (isIdenticalList(sam_answer, phone_presses)) {
          loadTheWin();
          return;
      }
      phone_presses = [];
      return;
  }
  if (phone_presses.length < 8) {
      phone_presses.push(dot);
      if (isIdenticalList(sam_answer, phone_presses)) {
        loadTheWin();
        return;
      }
  }
};

let safe_presses = [];
const safe_answer = [0, 1, 1, 6];

const safeButtons = (button) => {
  clickSound.play();
  if (button === "Enter" || safe_presses.length > 3) {
      if (isIdenticalList(safe_answer, safe_presses)) {
          loadTheWin();
          return;
      }
      safe_presses = [];
      document.getElementById("screen").innerHTML = "FAIL";
      return;
  }
  if (safe_presses.length < 4) {
      safe_presses.push(button);
      if (isIdenticalList(safe_answer, safe_presses)) {
        loadTheWin();
        return;
      }
      let numString = "";
      for (let i=0;i < safe_presses.length; i++) {
          numString += safe_presses[i].toString();
      }
      document.getElementById("screen").innerHTML = numString;
  }
};

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,
        "data": JSON.stringify(data_value)
    }));
    console.log("syncing");
    return combineDataSync(data_name, data_value);
};



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

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

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

const clickSound = new Audio("./assets/click.mp3");

const tapSound = new Audio("./assets/phone-tapping.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);

    // Handle the data

    data_locked_door = [{
        "expiration": newExpiration(30),
        "value": area
    }];

    syncPuzzleData("data_locked_door", data_locked_door);
};

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


let data_locked_door = [];

// 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 = [];

// 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 = {
            "area_1": 0,
            "area_2": 0,
            "area_3": 0,
            "area_4": 0,
            "area_5": 0,
            "area_6": 0
        };
        
        // Loop through the players' data and increment the dictionary we track
        for (const [expiration, value] of Object.entries(synced_data_value)) {
            for (let i=0; i < value.length; i++) {
                if (value[i] in new_locked_door_data) {
                    new_locked_door_data[value[i]]++;
                }
            }
        }
        
        console.log(new_locked_door_data);
        
        // Check if the player won
        for (const [area, value] of Object.entries(new_locked_door_data)) {
            console.log(value);
            if (value < 30) {
                return;
            }
        }
        // If we got down here, all values were above 9
        loadTheWin();
        return;
    }
};