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

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

import { _MODULE_CONFIG } from '../types/token';
import {
  VersionInfo2Request,
  VersionInfo2Response,
  encodeVersionInfo2,
  decodeVersionInfo2
} from '../apis/version-info2';
import {
  UpdateInfoRequest,
  UpdateInfoResponse,
  encodeUpdateInfo,
  decodeUpdateInfo
} from '../apis/update-info';
import { ModuleConfig } from '../types/module-config';

@Injectable({
  providedIn: 'root'
})
export class PublicApiService {
  constructor(
    @Inject(_MODULE_CONFIG) private moduleConfig: ModuleConfig,
    private httpClient: HttpClient
  ) {}

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

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