import { Injectable } from '@angular/core';

import { Observable } from 'rxjs';
import { map, takeWhile, take } from 'rxjs/operators';

import { ProtocolService } from '@ucap-webmessenger/protocol';
import {
  SSVC_TYPE_FILE_INFO_REQ,
  SVC_TYPE_FILE,
  SSVC_TYPE_FILE_INFO_RES,
  SSVC_TYPE_FILE_INFO_DATA,
  SSVC_TYPE_FILE_INFO_CHECK_DATA,
  SSVC_TYPE_FILE_DOWN_CHECK_REQ
} from '../types/service';
import {
  InfoRequest,
  InfoResponse,
  encodeInfo,
  decodeInfo,
  InfoData,
  InfoCheckData,
  decodeInfoData,
  decodeInfoCheckData
} from '../protocols/info';
import {
  DownCheckRequest,
  DownCheckResponse,
  encodeDownCheck,
  decodeDownCheck
} from '../protocols/down-check';
@Injectable({
  providedIn: 'root'
})
export class FileProtocolService {
  constructor(private protocolService: ProtocolService) {}

  public info(
    req: InfoRequest
  ): Observable<InfoResponse | InfoData | InfoCheckData> {
    return this.protocolService
      .call(SVC_TYPE_FILE, SSVC_TYPE_FILE_INFO_REQ, ...encodeInfo(req))
      .pipe(
        takeWhile(res => SSVC_TYPE_FILE_INFO_RES !== res.subServiceType, true),
        map(res => {
          if (SSVC_TYPE_FILE_INFO_DATA === res.subServiceType) {
            return decodeInfoData(res);
          } else if (SSVC_TYPE_FILE_INFO_CHECK_DATA === res.subServiceType) {
            return decodeInfoCheckData(res);
          }

          return decodeInfo(res);
        })
      );
  }

  public downCheck(req: DownCheckRequest): Observable<DownCheckResponse> {
    return this.protocolService
      .call(
        SVC_TYPE_FILE,
        SSVC_TYPE_FILE_DOWN_CHECK_REQ,
        ...encodeDownCheck(req)
      )
      .pipe(
        take(1),
        map(res => {
          return decodeDownCheck(res);
        })
      );
  }
}
