import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest
} from "@angular/common/http";
import {Observable} from "rxjs";
import {
  AppConfigService,
  ApplicationSettingsProvider,
  AppVersionService,
  TokenHeaderUtil
} from "@webbpm/base-package";
import {MfeConfigurationProvider} from "../provider/mfe-configuration.provider";
import {joinPath} from "../../../mfe-app-tools";

export class MfeHttpBackendInterceptor implements HttpInterceptor {
  private static readonly CONTENT_TYPE_HEADER = 'Content-Type';
  private static readonly ENABLE_VERSION_IN_URL: string = "enable.version.in.url";
  private static readonly BACKEND_URL: string = "backend.url";
  private static readonly BACKEND_CONTEXT: string = "backend.context";

  constructor(private appConfigService: AppConfigService,
              private appVersionService: AppVersionService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = TokenHeaderUtil.addHeader(
        req, MfeHttpBackendInterceptor.CONTENT_TYPE_HEADER, 'application/json;charset=UTF-8'
    );

    let overrideObj

    if (!req.url.startsWith(ApplicationSettingsProvider.RESOURCES_PATH)
        && !req.url.startsWith('http:') && !req.url.startsWith('https:')) {

      let appVersionInUrl = this.getVersion();
      let backendUrl = this.appConfigService.getParamValue(MfeHttpBackendInterceptor.BACKEND_URL);
      let backendContext = this.appConfigService.getParamValue(
          MfeHttpBackendInterceptor.BACKEND_CONTEXT);

      let url;

      if (backendUrl) {
        url = backendUrl;
      }
      else if (backendContext) {
        url = joinPath(
            MfeConfigurationProvider.MFE_BASE_URL,
            backendContext
        );
      }
      else {
        url = ApplicationSettingsProvider.BACKEND_URL;
      }

      overrideObj = {url: `${url}${appVersionInUrl}/${req.url}`};
    }
    return next.handle(req.clone(overrideObj));
  }

  private getVersion(): string {
    return this.appConfigService.getParamValue(MfeHttpBackendInterceptor.ENABLE_VERSION_IN_URL) ==
           "true" ? "-" + this.appVersionService.getAppVersion() : "";
  }
}