import { Subject, of } from 'rxjs';
import { takeUntil, take, map, catchError } from 'rxjs/operators';

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

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

import { VersionInfo2Response } from '@ucap/api-public';
import { LoginResponse } from '@ucap/protocol-authentication';
import {
  AuthResponse,
  UserInfoSS,
  DeptSearchType,
  DeptUserRequest
} from '@ucap/protocol-query';

import { LogService } from '@ucap/ng-logger';
import {
  LoginSelector,
  AuthorizationSelector,
  ConfigurationSelector
} from '@ucap/ng-store-authentication';
import { QueryProtocolService } from '@ucap/ng-protocol-query';
import {
  DepartmentSelector,
  PresenceActions
} from '@ucap/ng-store-organization';
import {
  FixedSizeVirtualScrollStrategy,
  VIRTUAL_SCROLL_STRATEGY
} from '@angular/cdk/scrolling';

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

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

@Component({
  selector: 'app-group-profile-list',
  templateUrl: './profile-list.component.html',
  styleUrls: ['./profile-list.component.scss'],
  providers: [
    {
      provide: VIRTUAL_SCROLL_STRATEGY,
      useClass: ProfileListVirtualScrollStrategy
    }
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProfileListComponent implements OnInit, OnDestroy {
  @Input()
  checkable = false;

  @Input()
  isDialog = false;

  @Input()
  set searchData(data: SearchData) {
    if (!this.loginRes) {
      this._searchData = data;
      return;
    }
    this.searchMember(data);
  }
  // tslint:disable-next-line: variable-name
  private _searchData: SearchData;

  @Input() selectedUser: UserInfoSS[];

  @Output()
  searched: EventEmitter<UserInfoSS[]> = new EventEmitter();

  @Output()
  toggleCheck: EventEmitter<{
    checked: boolean;
    userInfo: UserInfoSS;
  }> = new EventEmitter();

  set userInfos(userInfos: UserInfoSS[]) {
    this._userInfos = userInfos;
    this.searched.emit(userInfos);
  }
  get userInfos() {
    return this._userInfos;
  }
  // tslint:disable-next-line: variable-name
  _userInfos: UserInfoSS[] = [];

  loginRes: LoginResponse;
  versionInfo2Res: VersionInfo2Response;

  processing = false;

  private ngOnDestroySubject: Subject<void>;

  constructor(
    private queryProtocolService: QueryProtocolService,
    private store: Store<any>,
    private changeDetectorRef: ChangeDetectorRef,
    private logService: LogService
  ) {}

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

    this.store
      .pipe(
        takeUntil(this.ngOnDestroySubject),
        select(ConfigurationSelector.versionInfo2Response)
      )
      .subscribe((versionInfo2Res) => {
        this.versionInfo2Res = versionInfo2Res;
      });

    this.store
      .pipe(takeUntil(this.ngOnDestroySubject), select(LoginSelector.loginRes))
      .subscribe((loginRes) => {
        this.loginRes = loginRes;
        if (!!this._searchData) {
          this.searchMember(this._searchData);
          this._searchData = undefined;
        }
      });
  }

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

  /** 개별 체크여부 */
  getCheckedUser(userInfo: UserInfoSS) {
    if (!!this.selectedUser && this.selectedUser.length > 0) {
      return (
        this.selectedUser.filter((item) => item.seq === userInfo.seq).length > 0
      );
    }
    return false;
  }

  /** 개별선택(토글) 이벤트 */
  onChangeCheckUser(param: { checked: boolean; userInfo: UserInfoSS }) {
    this.toggleCheck.emit(param);
  }

  onOpenProfile(userInfo: UserInfoSS): void {
    alert('Open Profile');
  }

  private searchMember(searchData: SearchData) {
    if (!searchData) {
      return;
    }

    const req = {
      divCd: 'ORGS',
      companyCode: searchData.companyCode,
      searchRange: DeptSearchType.All,
      search: searchData.searchWord,
      senderCompanyCode: this.loginRes.userInfo.companyCode,
      senderEmployeeType: this.loginRes.userInfo.employeeType
    } as DeptUserRequest;

    this.processing = true;
    this.queryProtocolService
      .deptUser(req)
      .pipe(take(1))
      .subscribe(
        (data) => {
          this.userInfos = data.userInfos.sort((a, b) =>
            a.name < b.name ? -1 : a.name > b.name ? 1 : 0
          );
          this.changeDetectorRef.detectChanges();

          // 검색 결과에 따른 프레즌스 조회.
          const userSeqList: string[] = [];
          this.userInfos.map((user) => userSeqList.push(user.seq));

          if (userSeqList.length > 0) {
            this.store.dispatch(
              PresenceActions.bulkInfo({
                divCd: 'orgSrch',
                userSeqs: userSeqList
              })
            );
          }
        },
        (error) => {},
        () => {
          this.processing = false;
        }
      );
  }
}
