import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { Flug } from '../Modell/Flug';
import { IFlugdatenProxy } from './IFlugdatenProxy';

@Injectable() export class FlugdatenProxy  { // implements IFlugdatenProxy
 constructor(private http: HttpClient) {
 }
 url: string = "/app/daten/flugdaten.json";
 getAllAsObservable(): Observable<Flug[]> {
  // Daten von HTTP-Dienst laden
  console.log("FlugdatenProxy:lade von " + this.url);
  return this.http
   .get(this.url)
   .map(resp => { console.log("FlugdatenProxy:Geladen!"); return resp; })
   // .flatMap(x => x)
   .catch((error: any) => {
    console.log("!!! FlugdatenProxy:Fehler", error);
    return Observable.throw(error.json().error || 'Server error');
   })
 }
 getAllAsArray(callback: (name: Flug[]) => void) {
  console.log("getAll() 1");
  this.getAllAsObservable().subscribe(flugSet => { callback(flugSet); });
 }



 // getAllInternal(): Promise<Array<Flug>> {


 //     return this.http.get(this.url)
 //         .toPromise()
 //         .then(response => { console.log("OK. Geladen:", (response.json() as Flug[])); return (response.json() as Flug[]);  })
 //         .catch(this.handleError)


 //     //    const observable = this.http.get(this.url);
 //     //     const anotherObservable = observable.map((response : any) => response.json().data);
 //     //     console.log(anotherObservable);
 //     //     anotherObservable.subscribe((data)=> { FlugService.flugset = data;})
 //     //   console.log(FlugService.flugset);
 // }

 private handleError(error: any): Promise<any> {
  console.error('An error occurred', error); // for demo purposes only
  return Promise.reject(error.message || error);
 }
}