import { Component, OnInit, OnDestroy } from '@angular/core';

import { Store, select } from '@ngrx/store';

import { Company } from '@ucap-webmessenger/api-external';

import * as AppStore from '@app/store';
import * as AuthenticationStore from '@app/store/account/authentication';
import * as CompanyStore from '@app/store/setting/company';
import { Observable, Subscription } from 'rxjs';
import { Router } from '@angular/router';
import { tap, map } from 'rxjs/operators';
import {
  DialogService,
  AlertDialogComponent,
  AlertDialogData,
  AlertDialogResult
} from '@ucap-webmessenger/ui';
import { StringUtil } from '@ucap-webmessenger/core';

@Component({
  selector: 'app-page-account-login',
  templateUrl: './login.page.component.html',
  styleUrls: ['./login.page.component.scss']
})
export class LoginPageComponent implements OnInit, OnDestroy {
  companyList$: Observable<Company[]>;

  loginFailureCount: Subscription;

  defatulLoginBtnText: string;
  loginBtnText: string;
  loginBtnEnable: boolean;

  timeChecker: any;
  defatulWaitingTime: number;
  waitingTime: number;

  constructor(
    private store: Store<any>,
    private router: Router,
    private dialogService: DialogService
  ) {}

  ngOnInit(): void {
    this.defatulLoginBtnText = 'LOGIN';
    this.defatulWaitingTime = 5 * 60; // sec

    this.store.dispatch(
      CompanyStore.companyList({
        companyGroupCode: 'LG'
      })
    );

    this.companyList$ = this.store.pipe(
      select(AppStore.SettingSelector.CompanySelector.companyList)
    );

    this.loginFailureCount = this.store
      .pipe(
        select(AppStore.AccountSelector.AuthenticationSelector.loginFailCount),
        map(count => {
          if (count > 0) {
            if (count < 5) {
              this.dialogService.open<
                AlertDialogComponent,
                AlertDialogData,
                AlertDialogResult
              >(AlertDialogComponent, {
                width: '360px',
                data: {
                  title: 'Alert',
                  html: `아이디 또는 패스워드가<br/>일치하지 않습니다.`
                }
              });
            }

            if (count === 5) {
              this.dialogService.open<
                AlertDialogComponent,
                AlertDialogData,
                AlertDialogResult
              >(AlertDialogComponent, {
                width: '360px',
                data: {
                  title: 'Alert',
                  html: `비밀번호 오류 횟수 초과입니다.<br/>비밀번호를 확인하신 후<br/>잠시 후 다시 시작해 주세요.`
                }
              });

              this.timeChecker = setInterval(() => this.getCheckTime(), 1000);
            }
            return;
          } else {
            if (!!this.timeChecker) {
              clearInterval(this.timeChecker);
            }
            this.waitingTime = this.defatulWaitingTime;
            this.loginBtnText = this.defatulLoginBtnText;
            this.loginBtnEnable = true;
          }
        })
      )
      .subscribe();
  }

  ngOnDestroy(): void {
    if (!!this.loginFailureCount) {
      this.loginFailureCount.unsubscribe();
    }
  }

  getCheckTime() {
    if (this.waitingTime <= 0) {
      // reset.
      if (!!this.timeChecker) {
        clearInterval(this.timeChecker);
      }
      this.waitingTime = this.defatulWaitingTime;
      this.loginBtnText = this.defatulLoginBtnText;
      this.loginBtnEnable = true;
    } else {
      // wait.
      this.waitingTime = this.waitingTime - 1;

      this.loginBtnText = `${StringUtil.zeroFill(
        Math.floor(this.waitingTime / 60),
        2
      )}:${StringUtil.zeroFill(this.waitingTime % 60, 2)}`;
      this.loginBtnEnable = false;
    }
  }

  onLogin(value: {
    companyCode: string;
    loginId: string;
    loginPw: string;
    rememberMe: boolean;
    notValid: () => void;
  }) {
    this.store.dispatch(
      AuthenticationStore.webLogin({
        loginInfo: {
          companyCode: value.companyCode,
          companyGroupType: 'C',
          loginId: value.loginId,
          loginPw: value.loginPw
        },
        rememberMe: value.rememberMe
      })
    );
  }

  onClickTemplate() {
    this.router.navigate(['/template']);
  }
}
