package vs;

import java.io.StringReader;
import java.util.Date;

import jakarta.json.Json;
import jakarta.json.JsonObject;
import jakarta.json.JsonReader;
import jakarta.websocket.DecodeException;
import jakarta.websocket.Decoder;
import jakarta.websocket.EndpointConfig;

public class DataDecoder implements Decoder.Text<Messung> {

	@Override
	public void destroy() {
	}

	@Override
	public void init(EndpointConfig arg0) {
	}

	@Override
	public Messung decode(String messungData) throws DecodeException {
		JsonReader reader = Json.createReader(new StringReader(messungData));
		JsonObject messungJson = reader.readObject();
		Messung messung = new Messung();
		messung.setUnit(Messung.Unit.valueOf(messungJson.getString("unit")));
		messung.setObservation(Double.parseDouble(messungJson.getString("observation")));
		Messung.Place where = new Messung.Place();
		where.setLat(messungJson.getJsonObject("where").getInt("lat"));
		where.setLon(messungJson.getJsonObject("where").getInt("lon"));
		messung.setWhere(where);
		messung.setSensor(messungJson.getString("sensor"));
		messung.setWhen(new Date(messungJson.getJsonNumber("when").longValueExact()));
		reader.close();
		return messung;
	}

	@Override
	public boolean willDecode(String arg0) {
		return true;
	}

}
