/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.engine.types;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.MultiLineString;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.geom.PrecisionModel;
import org.locationtech.jts.io.InputStreamInStream;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKBReader;
import org.locationtech.jts.io.WKBWriter;
import org.locationtech.jts.io.WKTReader;

/**
 * Riskscape Type that represents geometry, e.g. points lines and polygons.
 * Accepts either {@link Geometry} instances or strings in well known text format (WKT)
 */
public class Geom extends SimpleType {

  public static final WKTReader READER = new WKTReader();

  // endian, type, plus num coordinates
  private static final int HOUSEKEEPING_BYTES = 3;
  private static final int NUM_DIMENSIONS = 2;

  /**
   * Finds the most specific RiskScape geometry {@link Type} that can represent javaType.
   *
   * @param javaType class of the geometry
   * @return most specific RiskScape geometry type
   */
  public static Type fromJavaType(Class<? extends Geometry> javaType) {
    if (LineString.class.isAssignableFrom(javaType)) {
      return Types.LINE;
    } else if (MultiLineString.class.isAssignableFrom(javaType)) {
      return MultiGeom.MULTI_LINE;
    } else if (Point.class.isAssignableFrom(javaType)) {
      return Types.POINT;
    } else if (MultiPoint.class.isAssignableFrom(javaType)) {
      return MultiGeom.MULTI_POINT;
    } else if (Polygon.class.isAssignableFrom(javaType)) {
      return Types.POLYGON;
    } else if (MultiPolygon.class.isAssignableFrom(javaType)) {
      return MultiGeom.MULTI_POLYGON;
    }
    return Types.GEOMETRY;
  }

  @Override
  public Object coerce(Object value) throws CoercionException {
    checkForNull(value);

    if (value instanceof String) {
      try {
        // WKT transform
        value = READER.read((String) value);
      } catch (ParseException e) {
        throw new CoercionException(value, this, "Could not parse well known text", e);
      }
    }
    if (internalType().isAssignableFrom(value.getClass())) {
      return value;
    } else {
      throw new CoercionException(value, this, "Can not coerce object of type %s", value.getClass());
    }
  }

  @Override
  public Class<?> internalType() {
    return Geometry.class;
  }

  @Override
  public int estimateSize(Object entry) {
    Geometry geom = (Geometry) entry;
    // assuming WKB, this seems fair
    return HOUSEKEEPING_BYTES + geom.getNumPoints() * NUM_DIMENSIONS * Double.BYTES;
  }

  @Override
  public void toBytes(DataOutputStream os, Object toWrite) throws IOException {
    Geometry geometry = (Geometry) toWrite;
    WKBWriter writer = new WKBWriter();
    byte[] bytes = writer.write(geometry);

    // 4 bytes of srid
    os.writeInt(geometry.getSRID());
    // 4 bytes of array length - wkb doesn't strictly need this, but it makes it easier for deserializing code to
    // handle the input (or in fact just skip it).
    os.writeInt(bytes.length);
    // then the bytes
    os.write(bytes);
  }

  @Override
  public Object fromBytes(DataInputStream in) throws IOException {
    try {
      int srid = in.readInt();
      in.readInt(); // throw away numbytes - we don't need to read this, as it's encoded in the wkb protocol
      GeometryFactory gf = new GeometryFactory(new PrecisionModel(), srid);
      WKBReader reader = new WKBReader(gf);
      return reader.read(new InputStreamInStream(in));
    } catch (ParseException e) {
      throw new IOException("Failed to parse bytes from underlying byte stream", e);
    }
  }

  @Override
  public String toString(Object value) {
    if (value instanceof Geometry) {
      Geometry geometry = (Geometry) value;
      return String.format("%s[%d pts]", geometry.getClass().getSimpleName(), geometry.getCoordinates().length);
    } else {
      return super.toString(value);
    }
  }

  /*
   * We used to have implementations for read and write, but it was untested, seemingly broken and not used.  So rather
   * than test and fix something we don't yet use, I've marked it as not implemented.
   */
  @Override
  public Object read(ByteBuffer buffer) {
    throw new RuntimeException("ByteBuffer deserialization not supported for geometry");
  }
  @Override
  public void write(ByteBuffer buffer, Object value) {
    throw new RuntimeException("ByteBuffer serialization not supported for geometry");
  }

  @Override
  protected String getTypeInformationId() {
    return "geometry";
  }

}
