import { Observable, Subject, combineLatest } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';

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

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

import {
  VirtualScrollStrategy,
  FixedSizeVirtualScrollStrategy,
  VIRTUAL_SCROLL_STRATEGY,
  CdkVirtualScrollViewport
} from '@angular/cdk/scrolling';

import { VersionInfo2Response } from '@ucap/api-public';
import { Company } from '@ucap/api-external';
import { LoginResponse } from '@ucap/protocol-authentication';
import { UserInfo, GroupDetailData } from '@ucap/protocol-sync';
import { DeptInfo } from '@ucap/protocol-query';

import { LogService } from '@ucap/ng-logger';
import { NodeType } from '@ucap/ng-ui-group';
import { SessionStorageService } from '@ucap/ng-web-storage';
import {
  LoginSelector,
  ConfigurationSelector
} from '@ucap/ng-store-authentication';
import { DepartmentSelector } from '@ucap/ng-store-organization';
import { BuddySelector, GroupSelector } from '@ucap/ng-store-group';

import { AppAuthenticationService } from '@app/services/app-authentication.service';
import { AppKey } from '@app/types/app-key.type';
import { LoginSession } from '@app/models/login-session';
import { environment } from '@environments';

export class TreeVirtualScrollStrategy extends FixedSizeVirtualScrollStrategy {
  constructor() {
    super(48, 250, 500); // (itemSize, minBufferPx, maxBufferPx)
  }
}

@Component({
  selector: 'app-sections-organization-tree',
  templateUrl: './tree.section.component.html',
  styleUrls: ['./tree.section.component.scss'],
  providers: [
    {
      provide: VIRTUAL_SCROLL_STRATEGY,
      useClass: TreeVirtualScrollStrategy
    }
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TreeSectionComponent implements OnInit, OnDestroy {
  treeData: {
    deptInfoList: DeptInfo[];
    displayRoot?: boolean;
  };

  loginRes: LoginResponse;

  private ngOnDestroySubject = new Subject<boolean>();

  constructor(
    private appAuthenticationService: AppAuthenticationService,
    private sessionStorageService: SessionStorageService,
    private store: Store<any>,
    private changeDetectorRef: ChangeDetectorRef,
    private logService: LogService
  ) {}

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

    combineLatest([
      this.store.pipe(select(LoginSelector.loginRes)),
      this.store.pipe(select(DepartmentSelector.departmentInfoList))
    ])
      .pipe(takeUntil(this.ngOnDestroySubject))
      .subscribe(([loginRes, deptInfoList]) => {
        this.loginRes = loginRes;
        this.treeData = {
          deptInfoList,
          displayRoot: environment.productConfig.organization.displayRoot
        };
        this.changeDetectorRef.markForCheck();
      });
  }

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