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 { ModuleConfig } from '../types/module-config';
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';

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

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

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

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

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