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

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

import java.util.Map;

import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;

import com.google.common.collect.ImmutableMap;

import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Types;

public class TupleTest {

  Struct struct = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER);
  Struct withChildren = Struct.of("foo", Types.TEXT, "struct", struct);

  Tuple tuple = new Tuple(struct);
  Tuple parent = new Tuple(withChildren);

  @Test
  public void canBeFilledWithAndQueriedForValues() {
    tuple.set("foo", "hi");
    tuple.set("bar", 2);

    assertEquals("hi", tuple.fetch("foo"));
    assertEquals(Integer.valueOf(2), tuple.fetch("bar"));

    parent.set("struct", tuple);

    assertSame(tuple, parent.fetch("struct"));
  }

  @Test
  public void canBeFilledWithValuesThatDontMatchStruct() {
    tuple.set("bar", "hi");
    tuple.set("foo", 2);

    assertEquals("hi", tuple.fetch("bar"));
    assertEquals(Integer.valueOf(2), tuple.fetch("foo"));

    parent.set("struct", tuple);

    assertSame(tuple, parent.fetch("struct"));
  }

  @Test
  public void canBeQueriedViaStructEntry() {
    tuple.set("foo", "hi");
    tuple.set("bar", 2);

    assertEquals("hi", tuple.fetch(struct.getEntry("foo")));
  }

  @Test
  public void canBeSetViaStructEntry() {
    tuple.set(struct.getEntry("bar"), 2);

    assertEquals(Integer.valueOf(2), tuple.fetch("bar"));
  }

  @Test(expected=AssertionError.class)
  public void throwsIfQueriedWithRandomStructEntry() {
    tuple.set("foo", "text");
    tuple.fetch(withChildren.getEntry("foo"));
  }

  @Test(expected=AssertionError.class)
  public void throwsIfSetWithUnknownMember() {
    tuple.set(withChildren.getEntry("foo"), "text");
  }

  @Test(expected=NoSuchMemberException.class)
  public void throwsIfGetWithUnknownMember() {
    tuple.fetch("foos");
  }

  @Test
  public void canBeQueriedForTypes() {
    assertEquals(Types.TEXT, tuple.getType("foo"));
    assertEquals(struct, parent.getType("struct"));
  }

  @Test
  public void canBeQueriedForChildren() {
    parent.set("struct", struct);
    assertSame(struct, parent.fetch("struct"));
  }

  @Test
  public void canAcceptNullValues() {
    tuple.set("foo", null);
    assertNull(tuple.fetch("foo"));
  }

  @Test
  public void valuesCanBeClearedViaExplicitRemoveMethod() {
    tuple.set("foo", "fooz");
    tuple.remove("foo");
    assertNull(tuple.fetch("foo"));
  }

  @Test(expected=IllegalArgumentException.class)
  public void queryingForNonExistantChildTupleThrows() {
    parent.fetchChild("foo");
  }

  @Test
  public void canCloneReturningAShallowCopyOfEntries() {
    String foo = "foo!";
    Integer bar = Integer.valueOf(2);
    tuple.set("foo", foo);
    tuple.set("bar", bar);

    Tuple clone = tuple.clone();
    assertEquals(tuple, clone);
    assertNotSame(tuple, clone);
    assertSame(struct, clone.getStruct());
    assertSame(foo, clone.fetch("foo"));
    assertSame(bar, clone.fetch("bar"));
  }

  @Test
  public void canCloneReturningARecursiveCopyOfChildTuples() {
    String foo = "foo!";
    Integer bar = Integer.valueOf(2);
    tuple.set("foo", foo);
    tuple.set("bar", bar);

    parent.set("struct", tuple);
    parent.set("foo", foo);

    Tuple clone = parent.clone();
    assertEquals(parent, clone);
    assertNotSame(parent, clone);
    assertNotSame(struct, parent.fetchChild("struct"));
    assertEquals(tuple, parent.fetchChild("struct"));
  }

  @Test
  public void tupleToStringDelegatesToTypeToString() throws Exception {
    struct = Struct.of("geom", Types.GEOMETRY, "text", Types.TEXT);

    LineString line = new GeometryFactory().createLineString(new Coordinate[] {
        new Coordinate(1,  1),
        new Coordinate(2, 2)});

    tuple = Tuple.ofValues(struct, line, "foo");

    assertEquals("{geom=LineString[2 pts], text=foo}", tuple.toString());
  }

  @Test
  public void willCoerceSimpleTuple() {
    Struct type = Struct.of("a", Types.TEXT, "b", Types.INTEGER);
    StructMember a = type.getMember("a").get();
    StructMember b = type.getMember("b").get();

    Tuple test = Tuple.coerce(type, ImmutableMap.builder()
        .put("a", "foo")
        .put("b", "10").build());

    assertThat(test.fetch(a), is("foo"));
    assertThat(test.fetch(b), is(10L));
  }

  @Test
  public void willCoerceNestedTuple() {
    Struct type = Struct.of("a", Types.TEXT, "b", Types.INTEGER);
    StructMember a = type.getMember("a").get();
    StructMember b = type.getMember("b").get();

    Struct parentType = Struct.of("nested", type);
    StructMember nested = parentType.getMember("nested").get();

    Tuple p = Tuple.ofValues(parentType, Tuple.coerce(type, ImmutableMap.builder()
        .put("a", "foo")
        .put("b", "10").build()));

    Tuple test = (Tuple)p.fetch(nested);
    assertThat(test.fetch(a), is("foo"));
    assertThat(test.fetch(b), is(10L));
  }

  @Test
  public void getBehavesLikeMapGet() throws Exception {
    struct = Struct.of("a", Types.TEXT, "b", Types.INTEGER);
    tuple = Tuple.ofValues(struct, "1", 10L);
    Map<String, Object> map = tuple.toMap();

    assertThat(map.get("a"), is("1"));
    assertThat(map.get("b"), is(10L));
    // fetch throws an exception, but map allows this
    assertThat(map.get("c"), nullValue());
  }

}
