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

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

import {
  CheckUserInfoExRequest,
  CheckUserInfoExResponse,
  encodeCheckUserInfoEx,
  decodeCheckUserInfoEx,
} from '../apis/check-user-info-ex';
import {
  CompanyListRequest,
  CompanyListResponse,
  encodeCompanyList,
  decodeCompanyList,
} from '../apis/company-list';
import {
  TokenUpdateRequest,
  TokenUpdateResponse,
  encodeTokenUpdate,
  decodeTokenUpdate,
} from '../apis/token-update';
import {
  UrlInfoResponse,
  UrlInfoRequest,
  encodeUrlInfo,
  decodeUrlInfo,
} from '../apis/url-info';

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

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

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

  public checkUserInfoEx(
    req: CheckUserInfoExRequest
  ): Observable<CheckUserInfoExResponse> {
    return this.httpClient
      .post<any>(
        this.urls.checkUserInfoEx,
        {},
        {
          params: encodeCheckUserInfoEx(req),
        }
      )
      .pipe(map(res => decodeCheckUserInfoEx(res)));
  }

  public companyList(req: CompanyListRequest): Observable<CompanyListResponse> {
    return this.httpClient
      .post<any>(
        this.urls.companyList,
        {},
        {
          params: encodeCompanyList(req),
        }
      )
      .pipe(map(res => decodeCompanyList(res)));
  }

  public tokenUpdate(req: TokenUpdateRequest): Observable<TokenUpdateResponse> {
    return this.httpClient
      .post<any>(
        this.urls.tokenUpdate,
        {},
        {
          params: encodeTokenUpdate(req),
        }
      )
      .pipe(map(res => decodeTokenUpdate(res)));
  }

  public urlInfo(req: UrlInfoRequest): Observable<UrlInfoResponse> {
    return this.httpClient
      .post<any>(
        this.urls.urlInfo,
        {},
        {
          params: encodeUrlInfo(req),
        }
      )
      .pipe(map(res => decodeUrlInfo(res)));
  }
}
