package com.kamco.cd.kamcoback.Innopam.utils;

import java.util.List;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.prep.PreparedGeometry;
import org.locationtech.jts.geom.prep.PreparedGeometryFactory;
import org.locationtech.jts.index.strtree.STRtree;

public class ShpPnuMatcher {

  public static String pickByIntersectionMax(STRtree index, Geometry target) {

    Envelope env = target.getEnvelopeInternal();

    @SuppressWarnings("unchecked")
    List<ShpIndexManager.ShpRow> rows = index.query(env);

    double best = 0;
    String bestPnu = null;

    for (ShpIndexManager.ShpRow row : rows) {

      PreparedGeometry prep = PreparedGeometryFactory.prepare(row.geom);

      if (prep.contains(target) || prep.covers(target)) {
        return row.pnu;
      }

      if (!prep.intersects(target)) {
        continue;
      }

      double area = row.geom.intersection(target).getArea();
      if (area > best) {
        best = area;
        bestPnu = row.pnu;
      }
    }
    return bestPnu;
  }
}
