import { JsonDecoder, Result, Ok } from 'ts.data.json';
import { HighPrecipEvent, HighPrecipEventTimeseries, Fields } from './HighPrecipEvent';

const HighPrecipEventDecoder = JsonDecoder.object<HighPrecipEvent>(
    {
        id: JsonDecoder.string,
        area: JsonDecoder.number,
        length: JsonDecoder.number,
        si: JsonDecoder.number,
        start: JsonDecoder.string.map(stringDate => new Date(stringDate))
    },
    'HighPrecipEvent'
);

export default class HighPrecipEventTimeseriesDecoder {
    public static decode(jsonData: any): HighPrecipEventTimeseries {
        let result: HighPrecipEventTimeseries = new HighPrecipEventTimeseries();

        if (jsonData && Array.isArray(jsonData)) {
            Array.from(jsonData).forEach(value => {
                let res: Result<HighPrecipEvent> = HighPrecipEventDecoder.decode(value);
                if (res instanceof Ok) {
                    result.events.push(res.value);
                }
            });
        }

        result.setTimeseriesField(Fields.SI);
        return result;
    }
}