import { Injectable } from '@angular/core';
import { CONSTANTS } from '../../utils/app.constants';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { MiscService } from './misc.service';
import { TranslateService } from '@ngx-translate/core';
import { environment } from '../../../environments/environment';
import { APP_URL_KEY } from '../../utils/enums';

@Injectable({
  providedIn: 'root'
})
export class HttpService {
  
  API_PATH = environment.apiPath.get(APP_URL_KEY.API_PATH)

  constructor(private translateService: TranslateService,
    private miscService: MiscService, private http: HttpClient
  ) { }

  getRequest(url: string, queryParams?: HttpParams, pathParams?: any, showLoader = true, options?: any) {

    const custId: any = localStorage.getItem("userId");
    let headers = new HttpHeaders().set("Content-Type", "application/json");

    const authorization = "Bearer " + localStorage.getItem('token');
    headers = headers.set("Authorization", authorization);
    headers = headers.set("cmpUserId", custId);
    let apiUrl = this.API_PATH + url;
    this.miscService.showLoader();
    apiUrl = this.replaceParamsWithValues(apiUrl, pathParams);

    try {
      let response = this.http.get(apiUrl, { headers: headers });

      if (!(response instanceof HttpErrorResponse)) {
        if (showLoader) {
          this.miscService.hideLoader();
        }
        return response;
      }
      else {
        this.miscService.handleError(this.translateService.instant('ServerError'));
        return null;
      }
    }
    catch (e) {
      console.log(e);
      return null;
    }
  }

  postRequest(url: string, data?: any, pathParams?: any, isMultipart = false, showLoader = true) {
    const custId = localStorage.getItem("userId");
    let headers = new HttpHeaders().set("Content-Type", "application/json");
    let apiUrl = this.API_PATH + url;
    this.miscService.showLoader();
    headers = headers.set("Authorization", "Bearer " + localStorage.getItem('token'));
    if (custId != null) {
      headers = headers.set("cmpUserId", custId);
    }
    apiUrl = this.replaceParamsWithValues(apiUrl, pathParams);

    let formData = data;
    formData = this.setCommonParams(formData);
    if (isMultipart) {
      formData = this.convertToFormData(data);
    }
    try {
      let response = this.http.post(apiUrl, formData, { headers: headers });

      if (!(response instanceof HttpErrorResponse)) {
        if (showLoader) {
          this.miscService.hideLoader();
        }
        return response;
      }
      else {
        this.miscService.handleError(this.translateService.instant('ServerError'));
        return null;
      }
    }
    catch (e) {
      console.log(e);
      return null;
    }
  }

  putRequest(url: string, data: any, pathParams?: any, isMultipart = false, showLoader = true) {
    const custId: any = localStorage.getItem("userId");
    let headers = new HttpHeaders().set("Content-Type", "application/json");
    headers = headers.set("cmpUserId", custId);
    headers = headers.set("Authorization", "Bearer " + localStorage.getItem('token'));
    let apiUrl = this.API_PATH + url;
    apiUrl = this.replaceParamsWithValues(apiUrl, pathParams);
    this.miscService.showLoader();
    let formData = data;
    formData = this.setCommonParams(formData);
    if (isMultipart) {
      formData = this.convertToFormData(data);
    }

    try {
      let response = this.http.put(apiUrl, formData, { headers: headers });

      if (!(response instanceof HttpErrorResponse)) {
        if (showLoader) {
          this.miscService.hideLoader();
        }
        return response;
      }
      else {
        this.miscService.handleError(this.translateService.instant('ServerError'));
        return null;
      }
    }
    catch (e) {
      console.log(e);
      return null;
    }
  }



  deleteRequest(url: any, data: any, pathParams?: any, isMultipart = false, showLoader = true) {
    const custId: any = localStorage.getItem("userId");
    let apiUrl = this.API_PATH + url;
    let headers = new HttpHeaders().set("Content-Type", "application/json");
    headers = headers.set("Authorization", "Bearer " + localStorage.getItem('token'));
    headers = headers.set("cmpUserId", custId);
    apiUrl = this.replaceParamsWithValues(apiUrl, pathParams);

    this.miscService.showLoader();
    let formData = data;
    formData = this.setCommonParams(formData);
    if (isMultipart) {
      formData = this.convertToFormData(data);
    }

    try {
      let response = this.http.delete(apiUrl, { headers: headers, body: formData });

      if (!(response instanceof HttpErrorResponse)) {
        if (showLoader) {
          this.miscService.hideLoader();
        }
        return response;
      }
      else {
        this.miscService.handleError(this.translateService.instant('ServerError'));
        return null;
      }
    }
    catch (e) {
      console.log(e);
      return null;
    }
  }
  addQueryParamsToUrl(url: any, queryParams: any) {
    if (queryParams && Object.keys(queryParams).length > 0) {
      let toReturn = url + '?';
      Object.keys(queryParams).forEach((key, index, arr) => {
        toReturn += `${key}=${queryParams[key]}`;
        toReturn += index === arr.length - 1 ? '' : '&';
      });
      return toReturn;
    }
    return url;
  }
  convertToFormData(data: any) {
    const formData = new FormData();
    Object.keys(data).forEach((k) => {
      formData.append(k, data[k]);
    });
    return formData;
  }
  replaceParamsWithValues(url: any, data: any) {
    data = data ?? {};
    data['porOrgacode'] = CONSTANTS.POR_ORGACODE;
    if (data && Object.keys(data).length > 0) {
      Object.keys(data).forEach((k) => {
        url = url.replace(`{${k}}`, data[k]);
      });
    }
    return url;
  }

  setCommonParams(data: any = {}) {
    data = data ?? {};
    data['porOrgacode'] = CONSTANTS.POR_ORGACODE;
    return data;
  }
}
