import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, of, throwError } from "rxjs";


import * as source from '../../assets/fake-data/airport-data.json';
import { delay, dematerialize, materialize, mergeMap } from "rxjs/operators";
import { DIRECTION, SortField } from "@xdf/commons";

const basePath = './service/airport';

@Injectable()
export class AirportFakeBackendInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const {url, method, headers, body} = req;
        const data = (source as any).default;
        return of(null)
        .pipe(mergeMap(handleRoute))
        .pipe(materialize())
        .pipe(delay(50))
        .pipe(dematerialize());

        function handleRoute() {
            switch(true) {
                case url.endsWith(basePath + '/page') && method === 'POST':
                    return pagination(body);

                case url.match(".*" + basePath) && method === 'GET':
                    console.log(url);
                    return getOne(url);
                
                default:
                    return next.handle(req);
            }
        }

        function pagination(body) {
            body.totalPages = 1;
            body.totalItems = 2;

            const page_number = body.currentPage;
            const page_size = body.itemsPerPage ? body.itemsPerPage : 5;

            if(body.sortFields.length > 0) {
                const sortField: SortField = body.sortFields[0];
                const sign = sortField.direction === DIRECTION.asc ? 1: -1;
                
                data.sort(function (a, b){
                    if((typeof a[sortField.field] === 'number') && (typeof b[sortField.field] === 'number')) {
                        if(a[sortField.field] > b[sortField.field]) {
                            return 1 * sign;
                        } else if (a[sortField.field] < b[sortField.field]) {
                            return -1 * sign;
                        }
                        return 0;
                    } else {
                        return a[sortField.field].localeCompare(b[sortField.field]) * sign;
                    }
                });
            }

            body.data = data.slice(page_number * page_size, (page_number + 1) * page_size);
            return ok(body);
        }

        function getData() {
            return ok(data);
        }

        function ok(bodyContent?) {
            return of(new HttpResponse({ status: 200, body: bodyContent}));
        }

        function error(message: string) {
            return throwError({error: {message}});
        }

        function getOne(url: string) {
            return ok(data);
        }
    }

}