import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpRequest } from '@angular/common/http';

import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import {
  VersionInfo2Request,
  VersionInfo2Response,
  encodeVersionInfo2,
  decodeVersionInfo2
} from '../apis/version-info2';
import {
  UpdateInfoRequest,
  UpdateInfoResponse,
  encodeUpdateInfo,
  decodeUpdateInfo
} from '../apis/update-info';

import { _MODULE_CONFIG } from '../config/token';
import { ModuleConfig } from '../config/module-config';
import { UrlConfig } from '@ucap-webmessenger/core';
import { Urls } from '../config/urls';

@Injectable({
  providedIn: 'root'
})
export class PublicApiService {
  readonly urls: Urls;

  constructor(
    @Inject(_MODULE_CONFIG) private moduleConfig: ModuleConfig,
    private httpClient: HttpClient
  ) {
    this.urls = UrlConfig.getUrls(
      this.moduleConfig.hostConfig,
      this.moduleConfig.urls
    );
  }

  public versionInfo2(
    req: VersionInfo2Request
  ): Observable<VersionInfo2Response> {
    return this.httpClient
      .post<any>(
        this.urls.versionInfo2,
        {},
        {
          params: encodeVersionInfo2(req)
        }
      )
      .pipe(map((res: any) => decodeVersionInfo2(res)));
  }

  public urlForVersionInfo2(req: VersionInfo2Request): string {
    const httpReq = new HttpRequest(
      'GET',
      this.urls.versionInfo2,
      {},
      {
        params: encodeVersionInfo2(req)
      }
    );

    return httpReq.urlWithParams;
  }

  public updateInfo(req: UpdateInfoRequest): Observable<UpdateInfoResponse> {
    return this.httpClient
      .post<any>(
        this.urls.updateInfo,
        {},
        {
          params: encodeUpdateInfo(req)
        }
      )
      .pipe(map(res => decodeUpdateInfo(res)));
  }
}
