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

import { Observable } from 'rxjs';
import { map, filter } 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 {
  PasswordInitStep1Request,
  encodePasswordInitStep1
} from '../apis/password-init-step1';

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> {
    const httpReq = new HttpRequest(
      'POST',
      this.urls.login2,
      encodeLogin2(req),
      { reportProgress: true }
    );

    return this.httpClient.request(httpReq).pipe(
      filter(event => {
        if (event instanceof HttpResponse) {
          return true;
        }
        return false;
      }),
      map(res => decodeLogin2((res as HttpResponse<any>).body))
    );
  }

  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
    );
  }

  /**
   * passwordInitStep1Url
   */
  public passwordInitStep1Url(req: PasswordInitStep1Request): string {
    return UrlUtil.format(
      this.urls.passwordInitStep1,
      encodePasswordInitStep1(req) as Parameter
    );
  }
}
