/*
 * https://github.com/morethanwords/tweb
 * Copyright (C) 2019-2021 Eduard Kuzmenko
 * https://github.com/morethanwords/tweb/blob/master/LICENSE
 */

import { putPreloader } from '../components/misc';
import mediaSizes from '../helpers/mediaSizes';
import { AccountPassword } from '../layer';
import appStateManager from '../lib/appManagers/appStateManager';
import passwordManager from '../lib/mtproto/passwordManager';
import Page from './page';
import pageIm from './pageIm';
import Button from '../components/button';
import PasswordInputField from '../components/passwordInputField';
import PasswordMonkey from '../components/monkeys/password';
import RichTextProcessor from '../lib/richtextprocessor';
import I18n from '../lib/langPack';
import LoginPage from './loginPage';
import { replaceContent } from '../helpers/dom';

const TEST = false;
let passwordInput: HTMLInputElement;

let onFirstMount = (): Promise<any> => {
  const page = new LoginPage({
    className: 'page-password',
    withInputWrapper: true,
    titleLangKey: 'Login.Password.Title',
    subtitleLangKey: 'Login.Password.Subtitle'
  });

  const btnNext = Button('btn-primary btn-color-primary');
  const btnNextI18n = new I18n.IntlElement({key: 'Login.Next'});

  btnNext.append(btnNextI18n.element);

  const passwordInputField = new PasswordInputField({
    label: 'LoginPassword',
    name: 'password'
  });

  passwordInput = passwordInputField.input as HTMLInputElement;

  page.inputWrapper.append(passwordInputField.container, btnNext);

  let getStateInterval: number;

  let getState = () => {
    // * just to check session relevance
    if(!getStateInterval) {
      getStateInterval = window.setInterval(getState, 10e3);
    }

    return !TEST && passwordManager.getState().then(_state => {
      state = _state;

      if(state.hint) {
        replaceContent(passwordInputField.label, RichTextProcessor.wrapEmojiText(state.hint));
      } else {
        passwordInputField.setLabel();
      }
    });
  };

  let state: AccountPassword;
  
  btnNext.addEventListener('click', function(this, e) {
    if(!passwordInput.value.length) {
      passwordInput.classList.add('error');
      return;
    }

    this.setAttribute('disabled', 'true');
    let value = passwordInput.value;

    btnNextI18n.update({key: 'PleaseWait'});
    const preloader = putPreloader(this);

    passwordManager.check(value, state).then((response) => {
      //console.log('passwordManager response:', response);
        
      switch(response._) {
        case 'auth.authorization':
          clearInterval(getStateInterval);
          pageIm.mount();
          if(monkey) monkey.remove();
          break;
        default:
          btnNext.removeAttribute('disabled');
          btnNextI18n.update({key: response._ as any});
          preloader.remove();
          break;
      }
    }).catch((err: any) => {
      btnNext.removeAttribute('disabled');
      passwordInputField.input.classList.add('error');
      
      switch(err.type) {
        default:
          //btnNext.innerText = err.type;
          btnNextI18n.update({key: 'PASSWORD_HASH_INVALID'});
          break;
      }

      preloader.remove();
  
      getState();
    });
  });

  passwordInput.addEventListener('keypress', function(this, e) {
    this.classList.remove('error');
    btnNextI18n.update({key: 'Login.Next'});

    if(e.key === 'Enter') {
      return btnNext.click();
    }
  });

  const size = mediaSizes.isMobile ? 100 : 166;
  const monkey = new PasswordMonkey(passwordInputField, size);
  page.imageDiv.append(monkey.container);
  return Promise.all([
    monkey.load(),
    getState()
  ]);
};

const page = new Page('page-password', true, onFirstMount, null, () => {
  //if(!isAppleMobile) {
    passwordInput.focus();
  //}

  appStateManager.pushToState('authState', {_: 'authStatePassword'});
  appStateManager.saveState();
});

export default page;
