import type Config from '../../types/config';
import type GPTAnswer from '../../types/gpt-answer';

/**
 * Handle textbox
 * @param config
 * @param inputList
 * @param gptAnswer
 * @returns
 */
function handleTextbox(
  config: Config,
  inputList: NodeListOf<HTMLElement>,
  gptAnswer: GPTAnswer
): boolean {
  const input = inputList[0] as HTMLInputElement | HTMLTextAreaElement;

  if (
    inputList.length !== 1 || // for now we don't handle many input text
    (input.tagName !== 'TEXTAREA' && input.type !== 'text')
  ) {
    return false;
  }

  const answerText =
    gptAnswer.response && 'correct_answer' in gptAnswer.response
      ? String((gptAnswer.response as any).correct_answer)
      : gptAnswer.rawResponse;

  if (config.typing) {
    let index = 0;

    const eventHandler = function (event: Event) {
      event.preventDefault();

      if ((<KeyboardEvent>event).key === 'Backspace' || index >= answerText.length) {
        input.removeEventListener('keydown', eventHandler);
        return;
      }

      input.value = answerText.slice(0, ++index);
    };

    input.addEventListener('keydown', eventHandler);
  } else {
    input.value = answerText;
  }

  return true;
}

export default handleTextbox;
