import { Injectable } from '@angular/core'
import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'

export class MeasuresItem {
    constructor(
        public $uri: string,
        public caption: string,
    ) {}
    get id(): string {
        return this.$uri.substr(this.$uri.lastIndexOf('/') + 1)
    }
    get name(): string {
        return this.caption || this.id
    }
}

export class MeasuresItemsList {
    constructor(
        public items: MeasuresItem[]
    ) {}
}


@Injectable()
export class DataService {
    constructor(private _http: HttpClient){ }

    getResources(): Observable<Object[]> {
        return this._http.get<Object[]>('/api/list')
    }

    getList(store: string): Observable<MeasuresItem[]> {
        return this._http.get<MeasuresItem[]>('/api/' + store).pipe(
            map(res => res.map(
                item => new MeasuresItem(item['$uri'], item['caption'])
            ))
        )
    }

    getValues(
        store: string,
        id: number,
        value: string,
        sampling?: string,
        format: string = 'json',
        rangeFrom?: string,
        rangeTo?: string
    ): Observable<HttpResponse<Object>> {
        let p = {}
        let s = {}
        p[store] = id
        if (rangeFrom && rangeTo) {
            p['time'] = {"$between": [rangeFrom, rangeTo]}
        }
        s['time'] = false
        let params = new HttpParams()
        .set('where', JSON.stringify(p))
        .set('sort', JSON.stringify(s))
        .set('resample', sampling)
        .set('format', format)
        // FIXME: add the name of the value to fetch
        return this._http.get<Object>(
            '/api/' + store + '/values/' + value,
            {
                params: params,
                observe: 'response'
            }
        )
    }
}
