import axios from 'axios';
import { ChangeWorkflowSettings } from './ChangeWorkflowSettings';
import { HighPrecipEventTimeseries } from './HighPrecipEvent';
import DateRange from 'dasf-web/lib/dateSelection/daterangepicker/DateRange';

import Geometry from 'ol/geom/Geometry';
import WKT from 'ol/format/WKT';
import { JsonConvert } from 'json2typescript';

export class HighPrecipDataAcquisition {

    private static readonly MAX_ROI_LENGTH = 2000;
    private static readonly SIMPLIFY_DELTA = 0.01;

    public static async getEvents(settings: ChangeWorkflowSettings): Promise<HighPrecipEventTimeseries> {
        let query = 'http://rz-vm154.gfz-potsdam.de:8080/highprecip/events/query?' + HighPrecipDataAcquisition.toQueryString(settings);

        console.log("requesting highprecip event timeseries from: " + query);

        let jsonConvert: JsonConvert = new JsonConvert();
        const response = await axios.get(query);
        let data: HighPrecipEventTimeseries = jsonConvert.deserializeObject(response.data[0], HighPrecipEventTimeseries);
        return data;
    }

    private static toQueryString(settings: ChangeWorkflowSettings): string {
        let qs = "";
        qs += HighPrecipDataAcquisition.toSubsetFilterString("start", settings.dateRange);

        let usedExtent = false;

        let roi: Geometry = settings.roiWgs84;
        if (roi) {

            let decimals = 6;
            let roiWkt = new WKT().writeGeometry(roi, { 'decimals': decimals });

            // phase one: reduce string length by reducing the number of decimals
            while (roiWkt.length > HighPrecipDataAcquisition.MAX_ROI_LENGTH && decimals > 3) {
                // the roi wkt string is too long for a request lets reduce the number of decimals until it migh fit
                --decimals;
                roiWkt = new WKT().writeGeometry(roi, { 'decimals': decimals });
            }

            // phase two: reduce string length by accuracy via simplifying the geometry
            let simplify = 0;
            while (roiWkt.length > HighPrecipDataAcquisition.MAX_ROI_LENGTH) {
                // even with reduced decimals, the string is still too long, so we have to simplify the polygon
                simplify += HighPrecipDataAcquisition.SIMPLIFY_DELTA;
                roiWkt = new WKT().writeGeometry(roi.simplify(simplify), { 'decimals': decimals });
            }

            qs += "&subset=intersects(" + roiWkt + ")";
        }

        return qs;
    }

    private static toSubsetFilterString(fieldName: string, dateRange: DateRange): string {
        return "subset=" + fieldName + "(" + dateRange.minDate.toISOString().substr(0, 10) + "," + dateRange.maxDate.toISOString().substr(0, 10) + ")"
    }
}