import {
  Component,
  OnInit,
  OnDestroy,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Input,
  EventEmitter,
  Output
} from '@angular/core';
import { UserInfo } from '@ucap/protocol-sync';
import { UserInfoSS, UserInfoF, UserInfoDN } from '@ucap/protocol-query';

import { Store, select } from '@ngrx/store';
import { takeUntil } from 'rxjs/operators';
import { CompanySelector } from '@ucap/ng-store-organization';
import { Subject } from 'rxjs';
import { Company } from '@ucap/api-external';
import { AppAuthenticationService } from '@app/services/app-authentication.service';

@Component({
  selector: 'ucap-local-organization-tenant-search',
  templateUrl: './tenant-search.component.html',
  styleUrls: ['./tenant-search.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TenantSearchComponent implements OnInit, OnDestroy {
  companyList: Company[];
  companyCode: string;

  @Output()
  keyDownEnter = new EventEmitter<{
    companyCode: string;
    searchWord: string;
  }>();

  @Output()
  searchCancel = new EventEmitter<any>();

  private ngOnDestroySubject = new Subject<boolean>();
  constructor(
    private changeDetectorRef: ChangeDetectorRef,
    private store: Store<any>,
    private appAuthenticationService: AppAuthenticationService
  ) {}

  ngOnInit(): void {
    const userStore = this.appAuthenticationService.getUserStore();
    this.companyCode = userStore.companyCode;

    this.store
      .pipe(
        takeUntil(this.ngOnDestroySubject),
        select(CompanySelector.companyList)
      )
      .subscribe((companyList) => {
        this.companyList = companyList;
      });
  }

  ngOnDestroy(): void {
    if (!!this.ngOnDestroySubject) {
      this.ngOnDestroySubject.complete();
    }
  }

  onKeyDownEnter(searchWord: string) {
    this.keyDownEnter.emit({ companyCode: this.companyCode, searchWord });
  }
  onClickCancel() {
    this.searchCancel.emit();
  }
}
