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

import { AircraftResp, AircraftReq } from '../models/aircraft';

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

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

  public getListOfAircrafts(simple: boolean = false): Observable<Array<AircraftResp>> {
    let url : string;
    if (simple === true) {
      url = `${this.apiUrl}/Aircraft/GetSimple`;
    } else {
      url = `${this.apiUrl}/Aircraft`;
    }

    let callToApi = this.http.get<Array<AircraftResp>>(url, { headers: this.headers });
    return this.serviceCacheApi.get<Array<AircraftResp>>(CacheApiKey.Aircraft, callToApi);
  }

  public addAircraft(aircraftName: string, dataImg: string) {
    const bodyNewAircraft: AircraftReq = {
      id: 0,
      name: aircraftName,
      imageData: dataImg
    };

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

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

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