/*
 * 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.typexp;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import org.hamcrest.Matchers;
import org.junit.Test;

import nz.org.riskscape.dsl.LexerException;
import nz.org.riskscape.dsl.UnexpectedTokenException;
import nz.org.riskscape.engine.Assert;
import nz.org.riskscape.engine.types.CoverageType;
import nz.org.riskscape.engine.types.Enumeration;
import nz.org.riskscape.engine.types.MultiGeom;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.RSList;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.types.WithinRange;
import nz.org.riskscape.engine.types.WithinSet;
import nz.org.riskscape.engine.typeset.TypeSet;

public class TypeBuilderTest {

  TypeSet typeSet = new TypeSet();
  DefaultTypeBuilder builder = new DefaultTypeBuilder(typeSet);

  @Test
  public void testSimpleTypes() {
    assertEquals(Types.TEXT, builder.build("text"));
    assertEquals(Types.INTEGER, builder.build("integer"));
    assertEquals(Types.FLOATING, builder.build("floating"));
    assertEquals(Types.GEOMETRY, builder.build("geometry"));
    assertEquals(Types.BOOLEAN, builder.build("boolean"));
    assertEquals(Types.DATE, builder.build("datetime"));
    assertEquals(Types.DECIMAL, builder.build("decimal"));
    assertEquals(Types.ANYTHING, builder.build("anything"));
  }

  @Test
  public void testGeometryTypes() {
    assertEquals(Types.LINE, builder.build("line"));
    assertEquals(Types.POINT, builder.build("point"));
    assertEquals(Types.POLYGON, builder.build("polygon"));

    assertEquals(MultiGeom.MULTI_LINE, builder.build("multiline"));
    assertEquals(MultiGeom.MULTI_POINT, builder.build("multipoint"));
    assertEquals(MultiGeom.MULTI_POLYGON, builder.build("multipolygon"));

  }

  @Test
  public void unrecognizedSimpleTypeGivesNiceErrorMessage() throws Exception {
   assertThat(Assert.assertThrows(UnknownTypeException.class, () -> builder.build("weird")).getMessage(),
       Matchers.containsString("No simple type named 'weird'"));
  }

  @Test
  public void canCreateAListOfText() throws Exception {
    Type t = builder.build("list(text)");
    assertTrue(t instanceof RSList);
    RSList list = (RSList)t;
    assertEquals(Types.TEXT, list.getMemberType());
  }

  @Test
  public void canCreateAOneBasedEnum() throws Exception {
    assertEquals(Enumeration.oneBased("foo", "bar", "baz"),
        builder.build("enum('foo', 'bar', 'baz')"));
  }

  @Test
  public void enumRequireConstantArgs()  {
    TypeArgumentException ex = Assert.assertThrows(TypeArgumentException.class, ()
        -> build("enum(foo, 'bar')"));

    assertThat(ex.getMessage(), containsString("argument 0 expected to be a constant"));
  }

  @Test
  public void canCreateAWithinSet() throws Exception {
    assertEquals(new WithinSet(Types.TEXT, "foo", "bar", "baz"),
        builder.build("set(text, 'foo', 'bar', 'baz')"));
  }

  @Test
  public void setCreationFailsIfArgNotCoerceable() throws Exception {
    TypeArgumentException ex = Assert.assertThrows(TypeArgumentException.class, ()
        -> build("set(integer, '1', 'bar')"));

    assertThat(ex.getMessage(), containsString("set: Argument 2 could not be coerced to Integer"));
  }

  @Test
  public void canCreateAWithinRange() throws Exception {
    assertEquals(new WithinRange(Types.INTEGER, 0L, 10L),
        builder.build("range(integer, 0, 10)"));
  }

  @Test
  public void canMakeSomethingNullable() throws Exception {
    assertEquals(Nullable.of(Types.TEXT),
        builder.build("nullable(text)"));
  }

  @Test
  public void canLookupALinkedType() throws Exception {
    assertEquals(typeSet.getLinkedType("foo-type"),
        builder.build("lookup('foo-type')"));
  }

  @Test
  public void canMakeAnEnumNullable() throws Exception {
    assertEquals(Nullable.of(Enumeration.oneBased("foo", "bar", "baz")),
        builder.build("nullable(enum('foo', 'bar', 'baz'))"));
  }

  @Test
  public void canMakeAStruct() throws Exception {
    assertEquals(Struct.of("foo", Types.TEXT, "bar", Nullable.of(Types.INTEGER)),
        builder.build("struct(foo: text, bar: nullable(integer))"));

    // struct attribute names can contain hypens
    assertEquals(Struct.of("foo_0-10", Types.INTEGER, "foo_10-20", Types.INTEGER),
        builder.build("struct(foo_0-10: integer, foo_10-20: integer)"));
  }

  @Test
  public void canMakeACoverage() throws Exception {
    assertEquals(
        new CoverageType(Types.TEXT),
        builder.build("coverage(text)"));
  }

  @Test
  public void coverageExpectsASingleTypeArgument() throws Exception {
    TypeArgumentException ex = Assert.assertThrows(TypeArgumentException.class, ()
        -> build("coverage(text, float)"));

    assertThat(ex.getMessage(), containsString("coverage: single argument expected"));

    ex = Assert.assertThrows(TypeArgumentException.class, ()
        -> build("coverage('text')"));

    assertThat(ex.getMessage(), containsString("coverage: expected a type"));
  }

  @Test
  public void lexerErrorIsWrappedInTypeBuildingException() throws Exception {
    assertThat(Assert.assertThrows(BadTypeExpressionException.class,
        () -> builder.build("%%%[]")).getProblem().getException(),
        instanceOf(LexerException.class));
  }

  @Test
  public void parserErrorIsWrappedInBadTypeExpressionException() throws Exception {
    assertThat(Assert.assertThrows(BadTypeExpressionException.class,
        () -> builder.build("foo(bar baz)")).getProblem().getException(),
        instanceOf(UnexpectedTokenException.class));
  }

  @Test
  public void definingAStringGivesBadTypeExpression() throws Exception {
    Assert.assertThrows(BadTypeExpressionException.class, () -> builder.build("'foo'"));
  }

  private Type build(String expression) {
    return builder.build(expression);
  }

}
