package cz.senslog.connector.model.converter;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import cz.senslog.connector.model.api.Converter;
import cz.senslog.connector.model.fofr.FofrModel;
import cz.senslog.connector.model.fofr.LocationTrack;
import cz.senslog.connector.model.fofr.ParcelUpdate;
import cz.senslog.connector.model.logger.LoggerModel;
import cz.senslog.connector.model.telemetry.TelemetryModel;
import org.json.JSONObject;

import java.time.format.DateTimeFormatter;
import java.util.Arrays;

public class FofrModelTelemetryModelConverter implements Converter<FofrModel, TelemetryModel> {

    @Override
    public TelemetryModel convert(FofrModel model) {

        JsonObject geoJSON = new JsonObject();
        geoJSON.addProperty("type", "FeatureCollection");
        JsonArray features = new JsonArray();
        geoJSON.add("features", features);

        for (ParcelUpdate update : model.getUpdates()) {
            for (LocationTrack location : update.getLocations()) {
                JsonObject feature = new JsonObject();
                features.add(feature);
                feature.addProperty("type", "Feature");

                JsonObject properties = new JsonObject();
                feature.add("properties", properties);
                properties.addProperty("unitId", update.getUnitId());
                properties.addProperty("timestamp", location.getTimestamp().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

                JsonObject geometry = new JsonObject();
                feature.add("geometry", geometry);
                geometry.addProperty("type", "Point");
                JsonArray coordinates = new JsonArray();
                coordinates.add(location.getLongitude());
                coordinates.add(location.getLatitude());
                coordinates.add(0); // altitude
                geometry.add("coordinates", coordinates);

            }
        }

        return new TelemetryModel(geoJSON.toString(), model.getFrom(), model.getTo());
    }
}
