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

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

import { _MODULE_CONFIG } from '../config/token';
import { ModuleConfig } from '../config/module-config';
import { Urls } from '../config/urls';
import { UrlConfig } from '@ucap-webmessenger/core';
import {
  CallRequest,
  CallResponse,
  encodeCall,
  decodeCall
} from '../apis/call';
import { NGXLogger } from 'ngx-logger';

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

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

  public sendCall(req: CallRequest): Observable<CallResponse> {
    return this.httpClient
      .post<any>(
        this.urls.sendCall,
        {},
        {
          params: encodeCall(req)
        }
      )
      .pipe(map(res => decodeCall(res)));
  }
}
