import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  ElementRef,
  ChangeDetectorRef
} from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Company } from '@ucap-webmessenger/api-external';
import { LocalStorageService } from '@ucap-webmessenger/web-storage';
import { LoginInfo, KEY_LOGIN_INFO } from '@app/types';

@Component({
  selector: 'ucap-account-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  @Input()
  companyList?: Company[];
  @Input()
  loginBtnText?: string;
  @Input()
  loginBtnEnable: boolean;

  @Output()
  login = new EventEmitter<{
    companyCode: string;
    loginId: string;
    loginPw: string;
    rememberMe: boolean;
    notValid: () => void;
  }>();

  @ViewChild('loginPw', { static: true }) loginPwElementRef: ElementRef;

  loginForm: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private changeDetectorRef: ChangeDetectorRef,
    private localStorageService: LocalStorageService
  ) {}

  ngOnInit() {
    const loginInfo: LoginInfo = this.localStorageService.get<LoginInfo>(
      KEY_LOGIN_INFO
    );
    this.loginForm = this.formBuilder.group({
      companyCode: ['', [Validators.required]],
      loginId: ['', [Validators.required]],
      loginPw: ['', Validators.required],
      remember: [false]
    });

    if (loginInfo && loginInfo.companyCode && loginInfo.loginId) {
      this.loginForm.get('companyCode').setValue(loginInfo.companyCode);
      this.loginForm.get('loginId').setValue(loginInfo.loginId);
      this.loginForm.get('remember').setValue(true);
      this.changeDetectorRef.detectChanges();
    }

    if (!this.loginBtnText || this.loginBtnText.trim().length === 0) {
      this.loginBtnText = 'LOGIN';
    }
  }

  onClickLogin() {
    this.login.emit({
      companyCode: this.loginForm.get('companyCode').value,
      loginId: this.loginForm.get('loginId').value,
      loginPw: this.loginForm.get('loginPw').value,
      rememberMe: this.loginForm.get('remember').value,
      notValid: () => {
        this.loginPwElementRef.nativeElement.focus();
      }
    });
  }
}
