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

import { ApiService, DataProvider, MeasuresItem } from '../openapi'

// 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(
        public api: ApiService,
    ) {}

    getResources(): Observable<DataProvider[]> {
        return this.api.listDataProvidersApiDataProvidersGet()
    }

    getList(store: string): Observable<MeasuresItem[]> {
        return this.api.getModelListApiDataProviderStoreGet({store: store})
    }

    getValues(
        store: string,
        id: number,
        value: string,
        sampling?: string,
        format: string = 'json',
        rangeFrom?: string,
        rangeTo?: string
    ): Observable<unknown> {
        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.api.getModelValuesApiStoreNameValuesValueGet(
            {
                storeName: store,
                value: value,
                where: JSON.stringify(p),
                resample: sampling
            }
        )
    }
}
