import { Injectable, Inject, Input } from '@angular/core';
import { Subject, Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { WeatherForecast } from './fetchdata';

const CREATE_ACTION = 'create';
const UPDATE_ACTION = 'update';
const REMOVE_ACTION = 'destroy';

@Injectable()
export class FetchDataService extends BehaviorSubject<any[]> {

    constructor(private http: Http) {
        super([]);
    }

    private data: WeatherForecast[] = [];
    assocguid: string

    public read() {
        const action = ''
        const data = []
        this.fetch(action, data, this.assocguid)
            .do(data => this.data = data)
            .subscribe(data => {
                this.extractData(data)
                super.next(data);

            });
    }


    public resetItem(dataItem: any) {
        if (!dataItem) { return; }

        //find orignal data item
        const originalDataItem = this.data.find(item => item.dateFormatted === dataItem.dateFormatted);

        //revert changes
        Object.assign(originalDataItem, dataItem);

        super.next(this.data);
    }

    private reset() {
        this.data = [];
    }

    private fetch(action: string = "", data?: WeatherForecast[], guid?: string): Observable<WeatherForecast[]> {

        var datatest = JSON.stringify(data)

        if (action == "") {
            let options = new RequestOptions();
            options.body = this.serializeModels(data);
            return this.http
                .get('api/SampleData/WeatherForecasts', options)
                .map(response => response.json()).catch(this.handleError);
        }
        throw Error('Internal REST Command Error')
    }

    private serializeModels(data?: any): string {
        return data ? `&models=${JSON.stringify([data])}` : '';
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }

    private extractData(data?: any) {
        data.forEach((d) => {
            d.doB = new Date(d.doB);
            d.dueDate = new Date(d.dueDate);
        });
        return data;
    }
}