import * as DivCommon from './div-page-common';

export default function LoginDivPage(element, listener) {

  const id = 'login';
  const className = LoginDivPage.name;

  let div = element.getChildByID(id);
  let connectButton = element.getChildByName('loginButton');
  let username = element.getChildByName('username');
  let connectionStatus = element.getChildByID('connectionStatus');
  let onlineGame = element.getChildByName('onlineGame');


  username.addEventListener("keyup", event => {
    if (connectButton.value === 'Connect') {
      if (event.key !== "Enter") return;
      connectButton.click();
      event.preventDefault();
    }
  });

  let eventListener = function (event) {
    let eventName = event.target.name;
    switch (eventName) {
      case "loginButton":
        if (connectButton.value === 'Connect') {
          if (username.value !== '') {
            connectButton.disabled = true;
            connectionStatus.innerText = 'Connecting...';
            username.disabled = true;
            listener.onRequestConnection(username.value).then(
              () => {
                connectionStatus.innerText = 'Connected as ' + username.value;
                this.username = username.value;
                onlineGame.disabled = false;
                connectButton.value = "Disconnect";
                connectButton.disabled = false;
              },
              (error) => {
                console.log(`Could not connect as ${username.value} : ${error}`);
                connectButton.disabled = false;
                connectionStatus.innerText = error;
                username.disabled = false;
              }
            );
          } else {
            connectionStatus.innerText = 'Not Connected : Enter Username';
          }
        } else {
          connectButton.disabled = true;
          connectionStatus.innerText = `Disconnecting ${this.username}...`;
          onlineGame.disabled = true;
          listener.onRequestDisconnection();
          connectionStatus.innerText = 'Not Connected';
          connectButton.value = "Connect";
          connectButton.disabled = false;
          username.value = '';
          this.username = username.value;
          username.disabled = false;
        }
        break;
      case "onlineGame":
        listener.onGoOnlineRoom();
        break;
      case "localGame":
        alert("Feature not yet implemented!");
        break;
      default:
        break;
    }
  };

  div.addEventListener('click', eventListener);

  let onShow = function () {

    connectionStatus.focus();
  };

  let onHide = function () {

  };

  let loginDivPage = {
    className,
    div,
    connectButton,
    username,
    connectionStatus,
    onlineGame,
    onShow,
    onHide
  };

  return Object.assign(
    loginDivPage,
    DivCommon.canShow(loginDivPage),
    DivCommon.canHide(loginDivPage),
    DivCommon.hasConnectionState(loginDivPage)
  );

}



