### ----------------------------------------------------
### -- GEOS
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: t/01-basic.rakutest
### ----------------------------------------------------
use Test;

use GEOS::Native;
use NativeCall;
use JSON::Fast;

my $ctx = GEOS_init_r();
GEOSContext_setNoticeHandler_r($ctx, &dummy_handler);
GEOSContext_setErrorHandler_r($ctx, &dummy_handler);

sub parse-it($wkt) {
  my $wkt-out;
  my $geojson-out;

  try {
    my $reader = GEOSWKTReader_create_r($ctx) or die "Could not create reader";
    my $geom-a = GEOSWKTReader_read_r($ctx, $reader, $wkt) or die "Could not read geometry '$wkt'";
    my $writer = GEOSWKTWriter_create_r($ctx) or die "Could not create writer";
    $wkt-out = GEOSWKTWriter_write_r($ctx, $writer, $geom-a) or die "Could not write geometry";

    my $geojson-writer = GEOSGeoJSONWriter_create_r($ctx) or die "Could not create GeoJSON writer";
    $geojson-out = GEOSGeoJSONWriter_writeGeometry_r($ctx, $geojson-writer, $geom-a, 1) or die "Could not write GeoJSON";

    CATCH {
      default {
        return "Error: $_";
        GEOSWKTWriter_destroy_r($ctx, $writer) if $writer;
        GEOSGeom_destroy_r($ctx, $geom-a) if $geom-a;
        GEOSWKTReader_destroy_r($ctx, $reader) if $reader;
        GEOSGeoJSONWriter_destroy_r($ctx, $geojson-writer) if $geojson-writer;
        GEOS_finish_r($ctx) if $ctx;
      }
    }
  }
  return ($wkt-out, $geojson-out);
}

my $wkt = "POINT (1 1)";
my ($wkt-out, $geojson-out) = parse-it("POINT (1 1)");
# sometimes this is "POINT (1.0000000000000000 1.0000000000000000)"
like $wkt-out, /POINT/, "WKT output";
is $wkt-out.comb(/ <[0..9.]>+ /).map(+*).join(" "), "1 1", "WKT coordinates";
if $wkt-out.contains("Error") {
  diag $wkt-out;
  bail-out;
}
my $geojson = from-json($geojson-out);
is $geojson<type>, "Point", "GeoJSON type";
is $geojson<coordinates>[0], 1, "GeoJSON x";
is $geojson<coordinates>[1], 1, "GeoJSON y";

$wkt = "POINT(1 BAD DATA )";
my $error = parse-it($wkt);
like $error, /Error/, "Error on bad WKT";

done-testing;



