/*
  input.js
  fffadedev
  08/28/25

  Manages input specifics for a Game
 */

const NO_LETTER = '_';

class Input
{
  constructor(game) {

    this.game = game;
    this.guessInput = new GuessInput();

    this.isInputActive = false;
    this.currentInput = [];

    this.prepareEventListeners();
  }

  // Prepares input events onto document
  prepareEventListeners()
  {
    document.addEventListener('keydown', (e) => {
      if(!this.isInputActive)
        return;

      if(e.key === 'Backspace') {
        this.deductLetter();
      }
      else if(/^[A-Za-z]+$/.test(e.key) && e.key.length <= 1) {
        this.addLetter(e.key.toUpperCase());
      }
      else if(e.key === 'Enter' && this.currentInput && this.currentInput.filter(l => l === NO_LETTER).length <= 0) {

        if(!this.game.verifyInput(this.currentInput.join('')))
          return;

        this.game.guesses.updateGuess(game.attempts, this.currentInput, game.wordle.split(''));
        this.game.checkGuess(this.currentInput.join(''));

        // Reset input and increment attempt
        this.reset();
      }

      // Update guess input display on UI
      this.guessInput.update(this.currentInput);

    });
  }

  reset() {
    this.currentInput = [NO_LETTER, NO_LETTER, NO_LETTER, NO_LETTER, NO_LETTER];
    this.guessInput.update(this.currentInput);
    console.log("Input has been reset.");
  }

  addLetter(letter) {
    const index = this.currentInput.indexOf(NO_LETTER); // Find first instance of blank space
    this.currentInput[index] = letter;
    console.log("New input: " + currentInput);
  }

  deductLetter() {
    let index = this.currentInput.indexOf(NO_LETTER); // Find first instance of blank space, previous space is last letter

    // Remove last letter if available
    if(index === -1)
      index = this.currentInput.length;

    if(index > 0)
      this.currentInput[index - 1] = NO_LETTER;
  }

  hide() {

  }
}
