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

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

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

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

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

  public get urls(): PiUrls {
    return this.moduleConfig.urls;
  }
}
