import { Timeseries, DateValuePair, Header } from "dasf-web/lib/model/Timeseries";
import { JsonProperty, JsonObject } from "json2typescript";
import {DateConverter} from "dasf-web/lib/model/JsonSerializeHelper";

@JsonObject("HighPrecipEvent")
export class HighPrecipEvent {
    @JsonProperty("id")
    public id: string = "";
    @JsonProperty("area")
    public area: number = 0;
    @JsonProperty("length")
    public length: number = 0;
    @JsonProperty("si")
    public si: number = 0;
    @JsonProperty("start", DateConverter)
    public start: Date = new Date();
    // {"area":1.2599999904632568,"id":"201601770","length":7,"si":0.029999999329447746,"start":"2016-06-03T01:00:00"}

}

export abstract class Fields {
    public static readonly AREA: Header = new Header("area", "m^2");
    public static readonly LENGTH: Header = new Header("length", "#");
    public static readonly SI: Header = new Header("severity_index", "si");
}

@JsonObject("HighPrecipEventTimeseries")
export class HighPrecipEventTimeseries extends Timeseries {
    @JsonProperty("events", [HighPrecipEvent])
    public events: HighPrecipEvent[];

    public constructor() {
        super();
        this.events = [];
        this.gid = 0;
        this.data = [];
        this.header = Fields.SI;
        this.version = "1.0";
    }

    public setTimeseriesField(fieldHeader: Header): void {
        this.header = fieldHeader;

        // update the data array
        this.updateDataField();
    }

    public updateDataField(): void {
        this.assertEqualLength();

        // update the data array according to current set header
        for (let i = 0; i < this.data.length; ++i) {
            let element = this.data[i];
            element.date = this.events[i].start;

            switch (this.header) {
                case Fields.AREA:
                    element.field = this.events[i].area;
                    break;
                case Fields.LENGTH:
                    element.field = this.events[i].length;
                    break;
                case Fields.SI:
                    element.field = this.events[i].si;
                    break;
            }
        }
    }

    private assertEqualLength(): void {
        while (this.data.length < this.events.length) {
            this.data.push(new DateValuePair());
        }

        while (this.data.length > this.events.length) {
            this.data.length = this.events.length;
        }
    }
}
