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

// libs
import * as moment from 'moment';


@Injectable()
export class UpdateDateHttpInterceptor implements HttpInterceptor {

	intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
		if (request.method === 'POST' || request.method === 'PUT') {
			this.shiftDates(request.body);
		}

		return next.handle(request);
	}

	shiftDates(body: any) {
		if (body === null || body === undefined) {
			return body;
		}

		if (typeof body !== 'object') {
			return body;
		}

		for (const key of Object.keys(body)) {
			const value = body[key];
			if (value instanceof Date) {
				body[key] = moment(value).utcOffset(0, true).format();
			} else if (typeof value === 'object') {
				this.shiftDates(value);
			}
		}
	}
}
