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


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

import java.math.BigDecimal;
import java.util.List;

import org.geotools.filter.FilterFactoryImpl;
import org.junit.Test;
import org.geotools.api.filter.spatial.Equals;

import org.locationtech.jts.geom.Coordinate;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.problem.ResultComputationException;

import org.junit.Before;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.types.RSList;

public class StructAccessExpressionUnitTest extends BaseStructAccessExpressionTest {

  Struct struct = Struct.
      of("text", Types.TEXT);

  Struct childStruct1 = Struct.
      of("text", Types.TEXT, "number", Types.INTEGER);

  Struct childStruct2 = Struct.
      of("words", Types.TEXT, "decimals", Types.DECIMAL);

  Struct parentStruct = Struct.of("child1", childStruct1).and("child2", childStruct2);
  Struct linkedParentStruct;

  @Before
  public void setup() {
    typeSet.add("linked-child1", childStruct1);
    typeSet.add("linked-child2", childStruct2);
    linkedParentStruct = Struct.of("child1", typeSet.getLinkedType("linked-child1"))
        .and("child2", typeSet.getLinkedType("linked-child2"));
  }

  @Test
  public void canAccessPropertiesFromAStruct() {
    StructAccessExpression expr = new StructAccessExpression("text");
    assertEquals("foo", expr.evaluate(new Tuple(struct).set("text", "foo")));
    assertEquals("sweet dealio", expr.evaluate(new Tuple(struct).set("text", "sweet dealio")));
  }

  @Test
  public void canQueryTypesFromAStruct() {
    StructAccessExpression expr = new StructAccessExpression("text");
    assertEquals(Types.TEXT, expr.evaluateType(struct).get());
  }

  @Test
  public void canQueryTypesFromANullableStruct() {
    StructAccessExpression expr = new StructAccessExpression("text");
    assertEquals(Nullable.of(Types.TEXT), expr.evaluateType(Nullable.of(struct)).get());
    assertNull(expr.evaluate(null));
  }


  @Test
  public void canAccessPropertiesFromAStructOfStructs() {
    Tuple value = new Tuple(parentStruct)
        .set("child1", new Tuple(childStruct1).set("text", "text 1").set("number", "4"))
        .set("child2", new Tuple(childStruct2).set("words", "these are my words").set("decimals",
            new BigDecimal("1.054")));

    StructAccessExpression expr1 = new StructAccessExpression("child1.text");
    assertEquals("text 1", expr1.evaluate(value));

    StructAccessExpression expr2 = new StructAccessExpression("child2.decimals");
    assertEquals(new BigDecimal("1.054"), expr2.evaluate(value));
  }

  @Test
  public void canAccessPropertiesFromAStructOfLinkedStructs() {
    Tuple value = new Tuple(linkedParentStruct)
        .set("child1", new Tuple(typeSet.get("linked-child1").asStruct())
            .set("text", "text 1").set("number", "4"))
        .set("child2", new Tuple(typeSet.get("linked-child2").asStruct())
        .set("words", "these are my words").set("decimals",
            new BigDecimal("1.054")));

    StructAccessExpression expr1 = new StructAccessExpression("child1.text");
    assertEquals("text 1", expr1.evaluate(value));

    StructAccessExpression expr2 = new StructAccessExpression("child2.decimals");
    assertEquals(new BigDecimal("1.054"), expr2.evaluate(value));
  }

  @Test
  public void canQueryTypeFromAStructOfLinkedStructs() {
    StructAccessExpression expr1 = new StructAccessExpression("child1.text");
    assertEquals(Types.TEXT, expr1.evaluateType(linkedParentStruct).get());

    StructAccessExpression expr2 = new StructAccessExpression("child2.decimals");
    assertEquals(Types.DECIMAL, expr2.evaluateType(linkedParentStruct).get());
  }

  @Test
  public void canCreateStructAccessExpressionFromStructAccessExpressionAndAdditionalPath() {
    Tuple value = new Tuple(parentStruct)
        .set("child1", new Tuple(childStruct1).set("text", "text 1").set("number", "4"))
        .set("child2", new Tuple(childStruct2).set("words", "these are my words").set("decimals",
            new BigDecimal("1.054")));

    StructAccessExpression expr1 = new StructAccessExpression("child1").and("text");
    assertEquals("text 1", expr1.evaluate(value));

    StructAccessExpression expr2 = new StructAccessExpression("child2").and("decimals");
    assertEquals(new BigDecimal("1.054"), expr2.evaluate(value));
  }

  @Test(expected=ResultComputationException.class)
  public void raisesAnExceptionIfAPropertyDoesNotExist() {
    StructAccessExpression expr = new StructAccessExpression("toast");
    expr.evaluate(new Tuple(struct).set("text", "foo"));
  }

  @Test
  public void returnsNullIfChildDoesnotExist() {
    Tuple value = new Tuple(parentStruct);
    StructAccessExpression expr1 = new StructAccessExpression("child1.text");
    assertNull(expr1.evaluate(value));
  }

  @Test
  public void canBeUsedWithOtherSpatialFunctionsFromOpenGis() {
    Struct withGeom = Struct.of("geom", Types.GEOMETRY);
    Struct alsoGeom = Struct.of("geometry", Types.GEOMETRY);
    Struct parent = withGeom.parent("lhs").add("rhs", alsoGeom);

    Tuple value = new Tuple(parent)
        .set("lhs", new Tuple(withGeom).set("geom", pointy))
        .set("rhs", new Tuple(alsoGeom).set("geometry", pointy));

    StructAccessExpression expr1 = new StructAccessExpression("lhs.geom");
    StructAccessExpression expr2 = new StructAccessExpression("rhs.geometry");
    FilterFactoryImpl filterFactory = new FilterFactoryImpl();
    Equals equals = filterFactory.equal(expr1, expr2);

    assertTrue(equals.evaluate(value));

    Tuple nonMatching = new Tuple(parent)
        .set("lhs", new Tuple(withGeom).set("geom", pointy))
        .set("rhs", new Tuple(alsoGeom).set("geometry", geometryFactory.createPoint(new Coordinate(2,  1))));

    assertFalse(equals.evaluate(nonMatching));
  }

  @Test
  public void structAccessExpressionEqualsIfMembersAreSame() {
    StructAccessExpression e1 = new StructAccessExpression("segment1.segment2.segment3");
    StructAccessExpression e2 = new StructAccessExpression("segment1", "segment2", "segment3");
    assertEquals(e1, e2);
    assertFalse(e1 == e2);
  }

  @Test
  public void subsequentLookupsOnTheSameTypeUseACachedStructMemberExpression() {
    Struct foo = Struct.of("foo", Types.TEXT);
    StructAccessExpression e = new StructAccessExpression("foo");

    Tuple tuple = Tuple.of(foo, "foo", "bar");
    // check that it builds one and caches it
    assertNull(e.getCachedExpression());
    assertEquals("bar", e.evaluate(tuple));
    assertNotNull(e.getCachedExpression());
    assertSame(foo, e.getCachedExpression().getRootStruct());
    assertEquals("bar", e.getCachedExpression().evaluate(tuple));

    StructMemberAccessExpression cachedExpression = mock(StructMemberAccessExpression.class);
    when(cachedExpression.getRootStruct()).thenReturn(foo);
    when(cachedExpression.evaluate(same(tuple))).thenReturn("baz");
    // now pickle the cache with our spy and check it is used
    e.setCachedExpression(cachedExpression);

    assertEquals("baz", e.evaluate(tuple));
    verify(cachedExpression).evaluate(same(tuple));
  }

  @Test
  public void subsequentLookupsOnDifferentTypesDoNotReuseACachedStructMemberExpression() {
    // even though these types are equivalent, they are not the same, so members can not be shared
    Struct foo1 = Struct.of("foo", Types.TEXT);
    Struct foo2 = Struct.of("foo", Types.TEXT);

    StructAccessExpression e = new StructAccessExpression("foo");

    Tuple tuple = Tuple.of(foo1, "foo", "bar");

    StructMemberAccessExpression cachedExpression = mock(StructMemberAccessExpression.class);
    when(cachedExpression.getRootStruct()).thenReturn(foo2);
    when(cachedExpression.evaluate(same(tuple))).thenReturn("baz");
    // now pickle the cache with our spy and check it is *not* used
    e.setCachedExpression(cachedExpression);

    assertEquals("bar", e.evaluate(tuple));
    verify(cachedExpression, never()).evaluate(any());
    assertNotNull(e.getCachedExpression());
    // our pickled expression should get thrown out
    assertNotSame(e.getCachedExpression(), cachedExpression);
  }

  @Test
  public void canEvaluateANullableList() {
    Struct hasList = Struct.of("list", Nullable.of(RSList.create(Types.INTEGER)));
    StructAccessExpression subject = new StructAccessExpression("list");

    List<Long> items = Lists.newArrayList(3L, 5L, 7L);
    Tuple tuple = Tuple.ofValues(hasList, items);
    assertThat(subject.evaluate(tuple, List.class), is(items));

    assertThat(subject.evaluate(Tuple.of(hasList), List.class), is(nullValue()));
  }
}

