import moment from 'moment';

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

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

  @Input()
  fixedCompanyCode: string;

  @Input()
  companyCode: string;

  @Input()
  loginId: string;

  @Input()
  disable = false;

  @Input()
  processing = false;

  @Input()
  loginTry: LoginTry;

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

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

  loginForm: FormGroup;
  companyCodeFormControl = new FormControl('');
  loginIdFormControl = new FormControl('');
  loginPwFormControl = new FormControl('');
  loginFailed = false;

  moment = moment;

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

  ngOnInit() {
    const companyCodeValidators: ValidatorFn[] = [Validators.required];
    this.companyCodeFormControl.setValidators(companyCodeValidators);
    if (!!this.fixedCompanyCode) {
      this.companyCodeFormControl.setValue(this.fixedCompanyCode);
    }
    if (!!this.companyCode) {
      this.companyCodeFormControl.setValue(this.companyCode);
    }
    const loginIdValidators: ValidatorFn[] = [Validators.required];
    this.loginIdFormControl.setValidators(loginIdValidators);
    if (!!this.loginId) {
      this.loginIdFormControl.setValue(this.loginId);
    }
    const loginPwValidators: ValidatorFn[] = [Validators.required];
    this.loginPwFormControl.setValidators(loginPwValidators);

    this.loginForm = this.formBuilder.group({
      companyCodeFormControl: this.companyCodeFormControl,
      loginIdFormControl: this.loginIdFormControl,
      loginPwFormControl: this.loginPwFormControl
    });

    this.changeDetectorRef.detectChanges();
  }

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