import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

import {
  Component,
  OnInit,
  OnDestroy,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Output,
  EventEmitter,
  Input
} from '@angular/core';

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

import { Company } from '@ucap/api-external';

import { LogService } from '@ucap/ng-logger';
import { CompanySelector } from '@ucap/ng-store-organization';

import { AppAuthenticationService } from '@app/services/app-authentication.service';
import { SearchData } from '../models/search-data';
import { UserStore } from '@app/models/user-store';

@Component({
  selector: 'app-organization-search-for-tenant',
  templateUrl: './search-for-tenant.component.html',
  styleUrls: ['./search-for-tenant.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SearchForTenantComponent implements OnInit, OnDestroy {
  @Output() searchDataChange: EventEmitter<SearchData> = new EventEmitter();
  @Input() set searchData(value: SearchData) {
    this._searchData = value;
    if (!this._searchData) {
      this._searchData = {
        companyCode: this.userStore.companyCode
      };
    } else {
      if (!this._searchData.companyCode) {
        this._searchData.companyCode = this.userStore.companyCode;
      }
    }
  }
  get searchData() {
    return this._searchData;
  }
  // tslint:disable-next-line: variable-name
  _searchData: SearchData;

  @Output()
  canceled: EventEmitter<void> = new EventEmitter();

  companyList: Company[];

  private ngOnDestroySubject = new Subject<boolean>();
  private userStore: UserStore;

  constructor(
    private appAuthenticationService: AppAuthenticationService,
    private store: Store<any>,
    private changeDetectorRef: ChangeDetectorRef,
    private logService: LogService
  ) {
    this.userStore = this.appAuthenticationService.getUserStore();
  }

  ngOnInit(): void {
    this.ngOnDestroySubject = new Subject<boolean>();

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

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

  onChanged(data: { companyCode: string; searchWord: string }): void {
    this.searchDataChange.emit({
      companyCode: data.companyCode,
      searchWord: data.searchWord
    });
  }

  onCanceled(): void {
    this.searchDataChange.emit({
      companyCode: '',
      searchWord: ''
    });
    this.canceled.emit();
  }

  // onCanceled(): void {
  //   this.canceled.emit();
  // }
}
