    001// License: GPL. For details, see LICENSE file.
    002package org.openstreetmap.josm.plugins.streetside.utils.api;
    003
    004import java.util.Objects;
    005
    006import javax.json.Json;
    007import javax.json.JsonArrayBuilder;
    008import javax.json.JsonObjectBuilder;
    009
    010import org.openstreetmap.josm.plugins.streetside.StreetsideImage;
    011
    012import org.openstreetmap.josm.plugins.streetside.StreetsideLocationChangeset;
    013
    014
    015public final class JsonLocationChangesetEncoder {
    016  private JsonLocationChangesetEncoder() {
    017    // Private constructor to avoid instantiation
    018  }
    019
    020  public static JsonObjectBuilder encodeLocationChangeset(StreetsideLocationChangeset changeset) {
    021    Objects.requireNonNull(changeset);
    022    final JsonArrayBuilder imgChanges = Json.createArrayBuilder();
    023    for (StreetsideImage img : changeset) {
    024      imgChanges.add(encodeImageChanges(img));
    025    }
    026    return Json.createObjectBuilder()
    027      .add("type", "location")
    028      .add("changes", imgChanges)
    029      .add("request_comment", "JOSM-created");
    030  }
    031
    032  private static JsonObjectBuilder encodeImageChanges(StreetsideImage img) {
    033    Objects.requireNonNull(img);
    034
    035    final JsonObjectBuilder to = Json.createObjectBuilder();
    036    if (!img.getTempLatLon().equalsEpsilon(img.getLatLon())) {
    037      to.add("geometry", Json.createObjectBuilder()
    038        .add("coordinates", Json.createArrayBuilder()
    039          .add(img.getTempLatLon().getX())
    040          .add(img.getTempLatLon().getY())
    041        ).add("type", "Point")
    042      );
    043    }
    044    if (Math.abs(img.getHe() - img.getTempHe()) > 1e-9) {
    045      to.add("properties", Json.createObjectBuilder().add("ca", img.getTempHe()));
    046    } else {
    047      to.add("properties", Json.createObjectBuilder());
    048    }
    049    if (!img.getTempLatLon().equalsEpsilon(img.getLatLon())) {
    050      to.add("type", "Feature");
    051    }
    052
    053    return Json.createObjectBuilder()
    054      .add("image_key", img.getId())
    055      .add("to", to);
    056  }
    057}