import { Injectable } from '@angular/core';
import {
  QueryProtocolService,
  DeptUserRequest,
  UserInfoSS,
  DeptUserResponse,
  SSVC_TYPE_QUERY_DEPT_USER_DATA,
  DeptUserData,
  SSVC_TYPE_QUERY_DEPT_USER_RES
} from '@ucap-webmessenger/protocol-query';
import { Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class OrganizationService {
  constructor(private queryProtocolService: QueryProtocolService) {}

  getDeptUser(
    req: DeptUserRequest
  ): Observable<{ userInfos: UserInfoSS[]; res: DeptUserResponse }> {
    return new Observable<{ userInfos: UserInfoSS[]; res: DeptUserResponse }>(
      subscriber => {
        const userInfos: UserInfoSS[] = [];

        this.queryProtocolService
          .deptUser(req)
          .pipe()
          .subscribe(
            res => {
              switch (res.SSVC_TYPE) {
                case SSVC_TYPE_QUERY_DEPT_USER_DATA:
                  userInfos.push(...(res as DeptUserData).userInfos);
                  break;
                case SSVC_TYPE_QUERY_DEPT_USER_RES:
                  userInfos.sort((a, b) =>
                    a.order < b.order
                      ? -1
                      : a.order > b.order
                      ? 1
                      : a.name < b.name
                      ? -1
                      : a.name > b.name
                      ? 1
                      : 0
                  );

                  subscriber.next({ userInfos, res: res as DeptUserResponse });

                  break;
              }
            },
            error => {
              subscriber.error(error);
            },
            () => {
              subscriber.complete();
            }
          );
      }
    );
  }
}
