import { InMemoryDbService } from 'angular-in-memory-web-api';
import { Observable, of } from 'rxjs';
import { HttpEvent, HttpResponse, HttpRequest } from '@angular/common/http';
import * as Const from '../consts';
import { AppLogsService } from './applogs.service';
import { Injectable } from '@angular/core';
import { delay } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class InMemoryDataService implements InMemoryDbService {

  constructor(private appLogsService: AppLogsService) { }
  createDb() {
    return {};
  }

  parseMockData(request: HttpRequest<any>, guid: string): Observable<HttpEvent<any>> {
    return undefined;
  }


  mockingInterception(request: HttpRequest<any>, splittedURL: string[], filterStr: string, guid: string) {
    let resp: Observable<HttpEvent<any>> = null;
    switch (request.method) {
      case 'PUT':
      case 'POST':
        resp = this.postMockData(request.body);
        break;
      case 'GET':
        resp = this.getMockData(splittedURL[4], filterStr);
        break;
      case 'DELETE':
        resp = this.deleteMockData(+splittedURL[5]);
        break;
    }
    if (resp) {
      this.appLogsService.dlog(splittedURL[4] + (splittedURL.length < 6 ? ': list' : ''), { guid: guid }, 'color:' + Const.EN_AppColors.returnRequestColor);
      return resp.pipe(delay(500));
    }
  }


  getMockData(entityBase: string, entityFilterstring: string): Observable<HttpEvent<any>> {
    return of(new HttpResponse(
      { status: 200, body: this.getFilteredDataList(entityFilterstring) }
    ));
  }

  postMockData(entity: any): Observable<HttpEvent<any>> {
    return of(new HttpResponse({ status: 200, body: Object.assign({}, entity) }));
  }

  deleteMockData(id: number): Observable<HttpEvent<any>> {
    return of(new HttpResponse({ status: 200 }));
  }

  getFilteredDataList(entityFilterstring: string): any {
    return null;
  }
}
