import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpParameterCodec,
  HttpParams,
  HttpRequest
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { CookiesHelper } from '../ui-api/helpers/cookies-helper';
import { ConfigService } from '@shared/config/config.service';
import { TokenStorageService } from '@shared/ui-api/token-storage.service';

// TODO(manu): move this logic to a new EncoderInterceptor
class CustomEncoder implements HttpParameterCodec {
  encodeKey(key: string): string {
    return encodeURIComponent(key);
  }

  encodeValue(value: string): string {
    return encodeURIComponent(value);
  }

  decodeKey(key: string): string {
    return decodeURIComponent(key);
  }

  decodeValue(value: string): string {
    return decodeURIComponent(value);
  }
}

function getCookie(name) {
  return CookiesHelper.getCookie(name);
}


@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private config: ConfigService, private tokenStorage: TokenStorageService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const params = new HttpParams({encoder: new CustomEncoder(), fromString: req.params.toString()});
    const updatedRequestParams = {
      withCredentials: true,
      params,
    } as any;
    let customHeaders = null;
    if (window.hasOwnProperty('setHeaders')) {
      // @ts-ignore
      customHeaders = window.setHeaders(req, getCookie);
    }

    let token: string;
    if (req.url.includes('/staffapi/stop-impersonation')) {
      token = this.tokenStorage.getPanelToken('staff');
    } else {
      token = this.tokenStorage.getToken();
    }
    if (token) {
      if (!customHeaders) {
        customHeaders = {};
      }

      customHeaders.Authorization = `Fleio-Token ${token}`;
    }

    if (customHeaders) {
      updatedRequestParams.setHeaders = customHeaders;
    }

    if (this.config.activeClientId) {
      updatedRequestParams.setParams = {
        active_client: this.config.activeClientId,
      };
    }

    const updatedRequest = req.clone(updatedRequestParams);

    return next.handle(updatedRequest);
  }
}
