var LOGIN_BUTTON = 'loginBtn';
var LOGIN_FORM = 'login-form';
var LOGIN_ERROR = 'login-error';
var EXTERNAL_SCRIPT_CONTAINER = 'external-script-container';
var NEXT_BUTTON = 'btnOK';
var DATE_STAMP = '190312';

var template = `
  <div data-type="${LOGIN_FORM}" class="login-form-container">
    <div class="login-form">
      <form name="loginForm">
        <div class="login-form__input-container">
          <label class="login-form__label" for="email">Email:</label>
          <input class="login-form__input" id="email" type="text" name="email">
        </div>
        <div class="login-form__input-container">
          <label class="login-form__label" for="pin">Pin:</label>
          <input class="login-form__input" id="pin" type="text" name="pin">
        </div>
      </form>
      <button data-event="${LOGIN_BUTTON}" class="login-form__send-button">Login</button>
      <div data-type="${LOGIN_ERROR}" class="login-form__error" hidden="">Wrong email/pin</div>
    </div>
  </div>
`;

function setMailInLocalStorage(appData, email) {
  var storageKey = appData.simbasis.ID + '-' + DATE_STAMP;

  var newLoadedData = Object.assign({}, JSON.parse(localStorage.getItem(storageKey)));
  if (newLoadedData && newLoadedData.eventsData) {
    newLoadedData.eventsData.email = email;
    localStorage.setItem(storageKey, JSON.stringify(newLoadedData));
  } else {
    throw new Error('Can not find data in Local Storage');
  }

}

function toggleNextButton(isVisible) {
  var nextButton = document.querySelector('[data-event="' + NEXT_BUTTON + '"]');

  if (nextButton) {
    nextButton.hidden = !isVisible;
  }
}

function hideLoginForm() {
  var loginForm = document.querySelector('[data-type="' + LOGIN_FORM + '"]');

  if (loginForm) {
    loginForm.hidden = true;
  }
}

function showLoginError() {
  var loginError = document.querySelector('[data-type="' + LOGIN_ERROR + '"]');

  if (loginError) {
    loginError.hidden = false;
  }
}

function login(appData, email, pin) {
  if (email && pin) {
    var getLastCipherFromAscii = function(ascii) {
      return Number(ascii.toString().substr(-1, 1));
    };

    var sim = appData.simbasis.SysName;
    var random = Number(pin[0]);

    var chM1 =
      email
        .split('@')[0]
        .substr(-1, 1)
        .charCodeAt(0) * random;
    var chM2 =
      email
        .split('@')[1]
        .substr(0, 1)
        .charCodeAt(0) * random;
    var chS1 = sim.substr(0, 1).charCodeAt(0) * random;
    var chS2 = sim.substr(-1, 1).charCodeAt(0) * random;

    var chM1L = getLastCipherFromAscii(chM1);
    var chM2L = getLastCipherFromAscii(chM2);
    var chS1L = getLastCipherFromAscii(chS1);
    var chS2L = getLastCipherFromAscii(chS2);

    var newPin = random * 10000 + chM1L * 1000 + chS1L * 100 + chM2L * 10 + chS2L;

    return newPin === Number(pin);
  }
  return false;
}

function clickBtnLogin(appData) {
  var email = document.forms.loginForm.elements.email.value;
  var pin = document.forms.loginForm.elements.pin.value;

  var isValid = login(appData, email, pin);

  return {
    valid: isValid,
    email: isValid ? email : '',
  };
}

function addLoginButtonListener(appData) {
  var loginButton = document.querySelector('[data-event="' + LOGIN_BUTTON + '"]');

  var clickListener = function() {
    var valid = clickBtnLogin(appData).valid;
    var email = clickBtnLogin(appData).email;

    if (valid) {
      hideLoginForm();
      toggleNextButton(true);
      setMailInLocalStorage(appData, email);
    } else {
      showLoginError();
    }
  };

  if (loginButton) {
    loginButton.addEventListener(loginButton.getAttribute('data-event-type') || 'click', clickListener);
  } else {
    throw new Error('Cant find a tag with [data-event="' + LOGIN_BUTTON + '"]');
  }
}

function main(appData) {
  var scriptContainer = document.querySelector('[data-type="' + EXTERNAL_SCRIPT_CONTAINER + '"]');

  var element = document.createElement('div');
  element.innerHTML = template;
  scriptContainer.appendChild(element.firstElementChild);

  addLoginButtonListener(appData);

  toggleNextButton(false);
}

main(appData);