import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators';

import { Injectable } from '@angular/core';
import { SortField, DIRECTION } from '@xdf/commons';


const basePath = '/service/agent';

const tableData: Array<any> = [
    {
        id: 361,
        name: 'BANCO DE CREDITO DEL PERU',
        version: '0.0.1',
        status: 'Activo',
        country: 'Perú',
        timezone: 'GMT-5',
        avatar: 'https://www.w3schools.com/howto/img_avatar.png'
    },
    {
        id: 362,
        name: 'BANCO CONTINENTAL',
        version: '0.0.5',
        status: 'Activo',
        country: 'Perú',
        timezone: 'GMT-5',
        avatar: 'https://lh3.googleusercontent.com/VHB9bVB8cTcnqwnu0nJqKYbiutRclnbGxTpwnayKB4vMxZj8pk1220Rg-6oQ68DwAkqO=s180-rw'
    },
    {
        id: 363,
        name: 'JUAN DE ARONA',
        version: '0.0.1',
        status: 'Activo',
        country: 'Perú',
        timezone: 'GMT-5',
        avatar: 'data:image/jpeg;base64,[encoded data, 7908 characters]'
    },
    {
        id: 364,
        name: 'JUAN DE ARONA 2',
        version: '0.0.1',
        status: 'Activo',
        country: 'Perú',
        timezone: 'GMT-5',
        avatar: 'https://www.w3schools.com/howto/img_avatar.png'
    }
];

const data: Array<any> = [
    {
        id: 361,
        name: 'BANCO DE CREDITO DEL PERU',
        version: '0.0.1',
        status: 'Activo',
        country: 'Perú',
        timezone: 'GMT-5',
        avatar: 'https://www.w3schools.com/howto/img_avatar.png'
    }
];

@Injectable()
export class AgentFakeBackendInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const { url, method, headers, body } = request;

        return of(null)
            .pipe(mergeMap(handleRoute))
            .pipe(materialize())
            .pipe(delay(10))
            .pipe(dematerialize());

        function handleRoute() {

            switch (true) {
                case url.endsWith(basePath + '/page') && method === 'POST':
                    return pagination(body);
                case url.indexOf(basePath + '/connection/data') !== -1 && method === 'GET ':
                    return ok({});
                case url.indexOf(basePath + '/') !== -1 && method === 'GET':
                    return ok(data);
                default:
                    // pass through any requests not handled above
                    return next.handle(request);
            }
        }

        function pagination(data: any) {
            data.totalItems = tableData.length;

            const pageNumber = data.currentPage;
            const pageSize = data.itemsPerPage ? data.itemsPerPage : 5;

            data.totalPages = Math.ceil(data.totalItems / pageSize);

            if (data.sortFields.length > 0) {
                const sortField: any = data.sortFields[0];
                if (sortField.direction === DIRECTION.asc) {
                    tableData.sort((a, b) => {
                        if (JSON.stringify(a[sortField.field]) > JSON.stringify(b[sortField.field])) {
                            return 1;
                        } else if (JSON.stringify(a[sortField.field]) < JSON.stringify(b[sortField.field])) {
                            return -1;
                        }
                        return 0;
                    });
                } else {
                    tableData.sort((a, b) => {
                        if (JSON.stringify(a[sortField.field]) < JSON.stringify(b[sortField.field])) {
                            return 1;
                        } else if (JSON.stringify(a[sortField.field]) > JSON.stringify(b[sortField.field])) {
                            return -1;
                        }
                        return 0;
                    });
                }
            }

            data.data = tableData.slice(pageNumber * pageSize, (pageNumber + 1) * pageSize);

            return ok(data);
        }


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

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


    }
}