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

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.junit.Ignore;
import org.junit.Test;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Types;

public class FlattenProjectionTest {

  Struct deepest = Struct.of("foo", Types.TEXT);
  Struct deep = Struct.of("deepest", deepest);
  Struct shallow = Struct.of("deep", deep);

  @Test
  public void testFlattenOnNonNestedStructDoesNothing() {
    List<Tuple> values = Lists.newArrayList(
        new Tuple(deepest).set("foo", "bar"),
        new Tuple(deepest).set("foo", "baz")
    );

    ListRelation relation = new ListRelation(deepest, values);

    Relation mapped = relation.project(new FlattenProjection("-")).get();

    assertEquals(values, mapped.stream().collect(Collectors.toList()));
    assertEquals(mapped.getType(), relation.getType());
  }

  @Test
  public void testFlattenOnNonNestedStructOneLevelDeep() {
    List<Tuple> values = Lists.newArrayList(
        new Tuple(deep).set("deepest", new Tuple(deepest).set("foo", "bar")),
        new Tuple(deep).set("deepest", new Tuple(deepest).set("foo", "baz"))
    );

    ListRelation relation = new ListRelation(deep, values);

    Relation mapped = relation.project(new FlattenProjection("+")).get();

    Struct expectedType = Struct.of("deepest+foo", Types.TEXT);
    List<Tuple> expectedValues = Lists.newArrayList(
        new Tuple(expectedType).set("deepest+foo", "bar"),
        new Tuple(expectedType).set("deepest+foo", "baz")
    );

    assertEquals(expectedValues, mapped.stream().collect(Collectors.toList()));
    assertEquals(expectedType, mapped.getType());
  }

  @Test
  public void testFlattenOnNonNestedStructTwoLevelsDeep() {
    List<Tuple> values = Lists.newArrayList(
        new Tuple(shallow).set("deep", new Tuple(deep).set("deepest", new Tuple(deepest).set("foo", "bar"))),
        new Tuple(shallow).set("deep", new Tuple(deep).set("deepest", new Tuple(deepest).set("foo", "baz")))
    );

    ListRelation relation = new ListRelation(shallow, values);

    Relation mapped = relation.project(new FlattenProjection(".")).get();

    Struct expectedType = Struct.of("deep.deepest.foo", Types.TEXT);
    List<Tuple> expectedValues = Lists.newArrayList(
        new Tuple(expectedType).set("deep.deepest.foo", "bar"),
        new Tuple(expectedType).set("deep.deepest.foo", "baz")
    );

    assertEquals(expectedValues, mapped.stream().collect(Collectors.toList()));
    assertEquals(expectedType, mapped.getType());
  }

  @Test
  public void canFlattenANullableStruct() throws Exception {
    deep = Struct.of("deepest", Nullable.of(deepest));
    Projector projector = new FlattenProjection(".").getProjectionFunction(deep).get();

    Struct expected = Struct.of("deepest.foo", Nullable.TEXT);
    assertEquals(expected, projector.getProjectedType());

    assertEquals(
        Tuple.ofValues(expected, "foo"),
        projector.apply(Tuple.ofValues(deep, Tuple.ofValues(deepest, "foo")))
    );
    assertEquals(
        Tuple.ofValues(expected),
        projector.apply(Tuple.ofValues(deep))
    );
  }

  @Test
  public void addsIndexesToAttributesWithDuplicateNames() {
    Struct child = Struct.of("bar", Types.TEXT);
    Struct parent = Struct.of("foo_bar", Types.INTEGER, "foo", child);
    assertThat(new FlattenProjection("_").getProjectionFunction(parent), Matchers.result(
        Matchers.projecting(Struct.of("foo_bar", Types.INTEGER, "foo_bar_1", Types.TEXT))
    ));
  }

  @Test
  public void addsIndexesToAttributesWithDuplicateNamesInEncounterOrder() {
    Struct child = Struct.of("bar", Types.TEXT);
    Struct parent = Struct.of("foo_bar", Types.INTEGER, "foo_bar_1", Types.INTEGER, "foo", child);
    assertThat(new FlattenProjection("_").getProjectionFunction(parent), Matchers.result(
        Matchers.projecting(
            // nested bar was encountered last, so gets index 2
            Struct.of("foo_bar", Types.INTEGER, "foo_bar_1", Types.INTEGER, "foo_bar_2", Types.TEXT)
        )
    ));

    parent = Struct.of("foo_bar", Types.INTEGER, "foo", child, "foo_bar_1", Types.INTEGER);
    assertThat(new FlattenProjection("_").getProjectionFunction(parent), Matchers.result(
        Matchers.projecting(
            // nested bar was encountered before existing `foo_bar_1` so replaces it,
            // then `foo_bar_1` becomes `foo_bar_1_1` not ideal but oh well.
            Struct.of("foo_bar", Types.INTEGER, "foo_bar_1", Types.TEXT, "foo_bar_1_1", Types.INTEGER)
        )
    ));
  }

  @Test
  @Ignore("not yet needing - mostly only useful for the type projection so far")
  public void attributesAreLinkedBack() throws Exception {
    Projector projector = new FlattenProjection(".").getProjectionFunction(shallow).get();
    Struct projected = projector.getProjectedType();
    Map<List<StructMember>, List<StructMember>> mapping = projector.getDirectMapping();

    List<StructMember> actualSourceList =
        mapping.get(Collections.singletonList(projected.getEntry("deep.deepest.foo")));

    List<StructMember> expectedSourceList =
        Arrays.asList(shallow.getEntry("deep"), deep.getEntry("deepest"), deepest.getEntry("foo"));

    assertEquals(expectedSourceList, actualSourceList);

  }


}
