import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  ElementRef
} from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Company } from '@ucap-webmessenger/api-external';

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

  @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) {}

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      companyCode: ['', [Validators.required]],
      loginId: ['', [Validators.required]],
      loginPw: ['', Validators.required]
    });
  }

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