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

import { take, map } from 'rxjs/operators';

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

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

import * as AuthenticationStore from '../../../store/account/authentication';

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

  constructor(
    private externalApiService: ExternalApiService,
    private store: Store<any>
  ) {}

  ngOnInit(): void {
    this.externalApiService
      .companyList({ companyGroupCode: 'LG' })
      .pipe(
        take(1),
        map((res: CompanyListResponse) => {
          this.companies = res.companyList;
        })
      )
      .subscribe();
  }

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