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

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

import { LogService } from '@ucap/ng-logger';
import { DeptInfo } from '@ucap/protocol-query';

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

@Component({
  selector: 'app-pages-ogranization-sidenav',
  templateUrl: './sidenav.page.component.html',
  styleUrls: ['./sidenav.page.component.scss']
})
export class SidenavPageComponent implements OnInit, OnDestroy {
  initialExpanded: number;

  private ngOnDestroySubject: Subject<void>;

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private changeDetectorRef: ChangeDetectorRef,
    private logService: LogService
  ) {
    this.logService.info('app-pages-ogranization-sidenav');
  }

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

    this.activatedRoute.queryParams
      .pipe(takeUntil(this.ngOnDestroySubject))
      .subscribe((params) => {
        if (!!params) {
          const deptSeq = params[QueryParams.DEPT_SEQ];
          if (!!deptSeq) {
            this.initialExpanded = Number(deptSeq);
          }
        }
      });
  }

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

  onClickedTree(node: DeptInfo) {
    const queryParams: Params = {};
    queryParams[QueryParams.DEPT_SEQ] = String(node.seq);
    queryParams[QueryParams.BY_SEARCH] = String(false);

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