<template>
  <h1>Wördle</h1>
  <button @click="createPuzzle">new Puzzle</button>
  <Trials
    :length="length"
    :currentTrial="current.trial"
    :backendResponse="current.backendResponse"
  />
  <Keyboard
    :add-letter="addLetter"
    :remove-letter="removeLetter"
    :submit="submit"
  />
</template>

<script setup lang="ts">
import Keyboard from "@/components/Keyboard.vue";
import { onMounted, reactive } from "vue";
import Trials from "@/components/Trials.vue";

let riddle: string = "";
let current = reactive({
  trial: "",
  backendResponse: {
    trial: "",
    is_in_dictionary: true,
    is_solved: false,
    colors: [],
  },
});

let props = defineProps<{ length: number }>();

function createPuzzle() {
  const request = new XMLHttpRequest();
  request.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      riddle = JSON.parse(request.responseText).riddle;
      current.trial = "";
    }
  };
  request.open("GET", "http://127.0.0.1:8889/create", true);
  request.send();
}

function addLetter(letter: string) {
  if (current.trial.length < props.length) {
    current.trial = current.trial + letter;
  }
}

function removeLetter() {
  current.trial = current.trial.substring(0, current.trial.length - 1);
}

function submit() {
  const xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      current.backendResponse = JSON.parse(xmlHttp.responseText);
      if (
        current.backendResponse.is_in_dictionary &&
        !current.backendResponse.is_solved
      ) {
        current.trial = "";
      }
    }
  };
  xmlHttp.open(
    "GET",
    "http://127.0.0.1:8889/try/" + current.trial + "?riddle=" + riddle,
    true
  );
  xmlHttp.send(null);
}

// TODO: handle keyboard events
// TODO: colorize keyboard

onMounted(createPuzzle);
</script>

<style scoped></style>
