import {HttpClient} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Subject} from 'rxjs'; import {catchError} from 'rxjs/operators'; import {HsConfig} from 'hslayers-ng'; import {FieldService} from './field.service'; import {ZonesService} from './zones.service'; export type Index = 'EVI' | 'RVI4S1'; @Injectable({providedIn: 'root'}) export class CalculatorService { availableDates: Array; availableProducts = ['EVI', 'RVI4S1']; dateRangeSelects: Subject<{date: string}> = new Subject(); dateCalendarSelects: Subject<{date: string}> = new Subject(); selectedDate; //selectedProduct; serviceBaseUrl = 'https://fieldcalc.lesprojekt.cz/'; private _datesLoading: boolean; private _zonesLoading: boolean; constructor( private fieldService: FieldService, private hsConfig: HsConfig, private httpClient: HttpClient, private zonesService: ZonesService ) { this.dateRangeSelects.subscribe(({date}) => { this.selectedDate = date; }); } noDates(): boolean { return this.availableDates === undefined; } /** * Call 'get_dates' API method */ async getDates({product}: {product: Index}) { this.availableDates = undefined; this._datesLoading = true; try { const data = await this.httpClient .get<{dates: string[]}>( (this.proxyEnabled() ? this.hsConfig.proxyPrefix : '') + this.serviceBaseUrl + 'get_dates?' + 'product=' + product + '¢roid=' + JSON.stringify(this.fieldService.getSelectedFieldCentroid()) ) .toPromise(); this._datesLoading = false; console.log('data received!'); console.log(data); this.availableDates = data.dates; /* Any previously selected date must be cleaned up * so it won't get sent to the API as a wrong param */ this.selectedDate = undefined; } catch (err) { this._datesLoading = false; console.error('Somethin fucked up!'); console.log(err); } } get datesLoading() { return this._datesLoading; } get zonesLoading() { return this._zonesLoading; } /** * Call 'get_zones' API method */ async getZones({product}: {product: Index}) { this._zonesLoading = true; try { const data = await this.httpClient .post( (this.proxyEnabled() ? this.hsConfig.proxyPrefix : '') + this.serviceBaseUrl + 'get_zones', { product, date: this.selectedDate, format: 'geojson', geojson: this.fieldService.getSelectedFieldGeoJSON(), }, { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, } ) .toPromise(); console.log('data received!'); console.log(data); this._zonesLoading = false; this.zonesService.updateZones(data); } catch (err) { this._zonesLoading = false; console.error('Somethin fucked up!'); console.log(err); } } private proxyEnabled(): boolean { return this.hsConfig.useProxy === undefined || this.hsConfig.useProxy; } }