import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpXsrfTokenExtractor } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
	providedIn: 'root'
})
export class HttpXsrfInterceptorService {
	constructor(private tokenExtractor: HttpXsrfTokenExtractor) { }

	intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
		// DEBUG
		console.log("[Interceptor] => REQ:", req);
		// END DEBUG
		const headerName = 'X-CSRF-TOKEN';
		const token = this.tokenExtractor.getToken() as string;
		// DEBUG
		console.log('[Interceptor] => token : ', token);
		// END DEBUG

		if (token != null && !req.headers.has(headerName)) {
			req = req.clone({
				headers: req.headers.set(headerName, token)
			});
		}
		return next.handle(req);
	}
}
