import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";

import { JumpTypeResp, JumpTypeReq } from "../models/jumpType";

import { BaseService } from "./base.service";
import { CacheApiKey } from "../models/cache-api-key.enum";

@Injectable()
export class JumpTypeService extends BaseService {
  constructor(private http: HttpClient) {
    super();
  }

  public getListOfJumpTypes(onlyTunnel: boolean = false): Observable<Array<JumpTypeResp>> {
    let callToApi = this.http.get<Array<JumpTypeResp>>(`${this.apiUrl}/JumpType${onlyTunnel ? "/tunnel" : ""}`, { headers: this.headers });
    return this.serviceCacheApi.get<Array<JumpTypeResp>>(CacheApiKey.JumpType, callToApi);
  }

  public getListOfJumpTypesForTunnel(): Observable<Array<JumpTypeResp>> {
    let callToApi = this.http.get<Array<JumpTypeResp>>(`${this.apiUrl}/JumpType/tunnel`, { headers: this.headers });
    return this.serviceCacheApi.get<Array<JumpTypeResp>>(CacheApiKey.TunnelJumpType, callToApi);
  }

  public addJumpType(jumptypetName: string) {
    const bodyJumpType: JumpTypeReq = {
      id: 0,
      name: jumptypetName
    };

    return this.http.post(`${this.apiUrl}/JumpType`,
                          bodyJumpType, 
                          { headers: this.headers });
  }

  public getById(id: number) : Observable<JumpTypeResp> {
    return this.serviceCacheApi.getByKey<Array<JumpTypeResp>>(CacheApiKey.JumpType)
                               .pipe(map(data => { 
                                 return data.find(f => f.id === id);
                               }));
  }

  public getFromCache(): Observable<Array<JumpTypeResp>> {
    return this.serviceCacheApi.getByKey<Array<JumpTypeResp>>(CacheApiKey.JumpType);
  }
}
