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

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

import {
  Login2Request,
  Login2Response,
  encodeLogin2,
  decodeLogin2,
} from '../apis/login2';
import { PrivacyTotalRequest, encodePrivacyTotal } from '../apis/privacy-total';
import { UrlUtil, Parameter } from '@ucap-webmessenger/api';
import {
  UserTermsActionRequest,
  UserTermsActionResponse,
  encodeUserTermsAction,
  decodeUserTermsAction,
} from '../apis/user-terms-action';

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 PiService {
  readonly urls: Urls;

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

  public login2(req: Login2Request): Observable<Login2Response> {
    return this.httpClient
      .post<any>(
        this.urls.login2,
        {},
        {
          params: encodeLogin2(req),
        }
      )
      .pipe(map(res => decodeLogin2(res)));
  }

  public userTermsAction(
    req: UserTermsActionRequest
  ): Observable<UserTermsActionResponse> {
    return this.httpClient
      .post<any>(
        this.urls.userTermsAction,
        {},
        {
          params: encodeUserTermsAction(req),
        }
      )
      .pipe(map(res => decodeUserTermsAction(res)));
  }

  /**
   * privacyTotalUrl
   */
  public privacyTotalUrl(req: PrivacyTotalRequest): string {
    return UrlUtil.format(
      this.urls.policyTotal,
      encodePrivacyTotal(req) as Parameter
    );
  }
}
