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

import { Component, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute, Router, Params } from '@angular/router';

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

import { ParamsUtil } from '@ucap/ng-core';

import { SearchData } from '@app/ucap/organization/models/search-data';

import { QueryParams } from '../types/params.type';

@Component({
  selector: 'app-pages-organization-index',
  templateUrl: './index.page.component.html',
  styleUrls: ['./index.page.component.scss']
})
export class IndexPageComponent implements OnInit, OnDestroy {
  set companySearchData(searchData: SearchData) {
    this._companySearchData = searchData;
    this.onChangedCompanySearch();
  }
  get companySearchData() {
    return this._companySearchData;
  }
  // tslint:disable-next-line: variable-name
  _companySearchData: SearchData;

  deptSearchData: SearchData;

  deptSeq: string;

  private ngOnDestroySubject: Subject<boolean>;

  constructor(
    private store: Store<any>,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private changeDetectorRef: ChangeDetectorRef
  ) {}

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

    this.activatedRoute.queryParams
      .pipe(takeUntil(this.ngOnDestroySubject))
      .subscribe((params) => {
        if (!!params) {
          const deptSeq = params[QueryParams.DEPT_SEQ];
          const companyCode = params[QueryParams.COMPANY_CODE];
          const searchWord = params[QueryParams.SEARCH_WORD];
          const bySearch = ParamsUtil.getParameter<boolean>(
            params,
            QueryParams.BY_SEARCH,
            false
          );

          this.deptSearchData = {
            deptSeq: bySearch ? undefined : deptSeq,
            companyCode: bySearch ? companyCode : undefined,
            searchWord: bySearch ? searchWord : undefined,
            bySearch
          };

          this._companySearchData = {
            ...this.deptSearchData
          };
        }
      });
  }

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

  onChangedCompanySearch() {
    const queryParams: Params = {};
    queryParams[QueryParams.COMPANY_CODE] = this._companySearchData.companyCode;
    queryParams[QueryParams.SEARCH_WORD] = this._companySearchData.searchWord;
    queryParams[QueryParams.BY_SEARCH] = String(true);

    this.router.navigate(
      [
        'organization',
        {
          outlets: { content: 'index' }
        }
      ],
      {
        queryParams
      }
    );
  }
}
