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

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;

import nz.org.riskscape.engine.output.StructFlattener.StructMapping;
import nz.org.riskscape.engine.types.CoercionException;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.engine.types.WrappingType;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

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

public class StructFlattenerTest {

  private StructFlattener subject;

  @Before
  public void setup() {
    subject = new StructFlattener();
  }

  @Test
  public void canMapFlatStructs() {
    Struct myStruct = Struct.of("the_geom", Types.GEOMETRY)
        .and("name", Types.TEXT)
        .and("desc", Types.TEXT)
        .build();

    List<StructMapping> mappings = subject.flatten(myStruct);
    assertEquals(3, mappings.size());
    ensurePresent(mappings, "the_geom", "the_geom");
    ensurePresent(mappings, "name", "name");
    ensurePresent(mappings, "desc", "desc");
  }

  @Test
  public void canMapNestedStructs() {
    Struct nestedStruct = Struct.of("name", Types.TEXT).and("desc", Types.TEXT).build();
    Struct myStruct = Struct.of("the_geom", Types.GEOMETRY)
        .and("a", nestedStruct)
        .and("b", nestedStruct)
        .build();

    List<StructMapping> mappings = subject.flatten(myStruct);
    assertEquals(5, mappings.size());
    ensurePresent(mappings, "the_geom", "the_geom");
    ensurePresent(mappings, "a.name", "a", "name");
    ensurePresent(mappings, "a.desc", "a", "desc");
    ensurePresent(mappings, "b.name", "b", "name");
    ensurePresent(mappings, "b.desc", "b", "desc");
  }

  @Test
  public void canMapNullableNestedStructs() {
    Struct nestedStruct = Struct.of("name", Types.TEXT).and("desc", Types.TEXT).build();
    Struct myStruct = Struct.of("the_geom", Types.GEOMETRY)
        .and("a", Nullable.of(nestedStruct))
        .and("b", nestedStruct);

    List<StructMapping> mappings = subject.flatten(myStruct);
    assertEquals(5, mappings.size());
    ensurePresent(mappings, "the_geom", "the_geom");
    ensurePresent(mappings, "a.name", "a", "name");
    ensurePresent(mappings, "a.desc", "a", "desc");
    ensurePresent(mappings, "b.name", "b", "name");
    ensurePresent(mappings, "b.desc", "b", "desc");
  }

  @Test
  public void canMapWrappedNestedStructs() {
    Struct nestedStruct = Struct.of("name", Types.TEXT).and("desc", Types.TEXT).build();
    WrappingType wrapped = new WrappingType() {
      @Override
      public Type getUnderlyingType() {
        return nestedStruct;
      }

      @Override
      public Object coerce(Object value) throws CoercionException {
        return getUnderlyingType().coerce(value);
      }

      @Override
      public Class<?> internalType() {
        return nestedStruct.internalType();
      }

      @Override
      public void toBytes(DataOutputStream os, Object toWrite) throws IOException {
      }

      @Override
      public Object fromBytes(DataInputStream in) throws IOException {
        return null;
      }
    };
    Struct myStruct = Struct.of("the_geom", Types.GEOMETRY)
        .and("a", wrapped)
        .and("b", wrapped)
        .build();

    List<StructMapping> mappings = subject.flatten(myStruct);
    assertEquals(5, mappings.size());
    ensurePresent(mappings, "the_geom", "the_geom");
    ensurePresent(mappings, "a.name", "a", "name");
    ensurePresent(mappings, "a.desc", "a", "desc");
    ensurePresent(mappings, "b.name", "b", "name");
    ensurePresent(mappings, "b.desc", "b", "desc");
  }

  @Test
  public void canMapFlatStructsAndShortenKeys() {
    Struct myStruct = Struct.of("name-that-is-too-long", Types.TEXT)
        .and("desc-that-is-too-long", Types.TEXT)
        .build();

    List<StructMapping> mappings = subject.flatten(myStruct);
    subject.shortenIfNecessary(mappings, 4);
    assertEquals(2, mappings.size());
    ensurePresent(mappings, "name", "name-that-is-too-long");
    ensurePresent(mappings, "desc", "desc-that-is-too-long");
  }

  @Test
  public void canMapNestedStructsAndShortenKeys() {
    Struct nestedStruct = Struct.of("name-of0", Types.TEXT)
        .and("name-of1", Types.TEXT)
        .and("name-of2", Types.TEXT)
        .and("name-of3", Types.TEXT)
        .and("name-of4", Types.TEXT)
        .and("name-of5", Types.TEXT)
        .and("name-of6", Types.TEXT)
        .and("name-of7", Types.TEXT)
        .and("name-of8", Types.TEXT)
        .and("name-of9", Types.TEXT)
        .and("desc", Types.TEXT).build();
    Struct myStruct = Struct.of("the_geom", Types.GEOMETRY)
        .and("a-item-with-long-name", nestedStruct)
        .build();

    List<StructMapping> mappings = subject.flatten(myStruct);
    subject.shortenIfNecessary(mappings, 4);
    assertEquals(12, mappings.size());
    ensurePresent(mappings, "the_", "the_geom");
    ensurePresent(mappings, "a.n0", "a-item-with-long-name", "name-of0");
    ensurePresent(mappings, "a.n1", "a-item-with-long-name", "name-of1");
    ensurePresent(mappings, "a.n2", "a-item-with-long-name", "name-of2");
    ensurePresent(mappings, "a.n3", "a-item-with-long-name", "name-of3");
    ensurePresent(mappings, "a.n4", "a-item-with-long-name", "name-of4");
    ensurePresent(mappings, "a.n5", "a-item-with-long-name", "name-of5");
    ensurePresent(mappings, "a.n6", "a-item-with-long-name", "name-of6");
    ensurePresent(mappings, "a.n7", "a-item-with-long-name", "name-of7");
    ensurePresent(mappings, "a.n8", "a-item-with-long-name", "name-of8");
    ensurePresent(mappings, "a.n9", "a-item-with-long-name", "name-of9");
    ensurePresent(mappings, "a.de", "a-item-with-long-name", "desc");
  }

  @Test
  public void canMapAndShortedNestedStructs() {
    Struct nestedStruct = Struct.of("name", Types.TEXT).and("desc", Types.TEXT);
    Struct myStruct = Struct.of("nested1", nestedStruct)
        .and("nested2", nestedStruct);

    List<StructMapping> mappings = subject.flatten(myStruct);
    subject.shortenIfNecessary(mappings, 10);
    assertEquals(4, mappings.size());
    ensurePresent(mappings, "n1.name", "nested1", "name");
    ensurePresent(mappings, "n1.desc", "nested1", "desc");
    ensurePresent(mappings, "n2.name", "nested2", "name");
    ensurePresent(mappings, "n2.desc", "nested2", "desc");
  }

  @Test(expected = IllegalArgumentException.class)
  public void canNotShortenWhenTooManyNamesMatch() {
    Struct nestedStruct = Struct.of("name-of0", Types.TEXT)
        .and("name-of1", Types.TEXT)
        .and("name-of2", Types.TEXT)
        .and("name-of3", Types.TEXT)
        .and("name-of4", Types.TEXT)
        .and("name-of5", Types.TEXT)
        .and("name-of6", Types.TEXT)
        .and("name-of7", Types.TEXT)
        .and("name-of8", Types.TEXT)
        .and("name-of9", Types.TEXT)
        .and("name-of10", Types.TEXT)
        .and("desc", Types.TEXT).build();
    Struct myStruct = Struct.of("the_geom", Types.GEOMETRY)
        .and("a-item-with-long-name", nestedStruct)
        .build();

    List<StructMapping> mappings = subject.flatten(myStruct);
    subject.shortenIfNecessary(mappings, 4);
  }

  @Test
  public void canShortenKeys() {
    assertThat(subject.shortenKey("hazard"), is("h"));
    assertThat(subject.shortenKey("hazard1"), is("h1"));
    assertThat(subject.shortenKey("hazard12"), is("h12"));
    assertThat(subject.shortenKey("1"), is("1"));
    assertThat(subject.shortenKey("12"), is("12"));
  }

  @Test
  public void canNameFromLastMemberOnly() {
    Struct child = Struct.of("a", Types.TEXT, "a1", Types.TEXT);

    StructFlattener.Namer namer = new StructFlattener.LastMemberNamer();
    List<StructMapping> mappings = subject.flatten(Struct.of("c1", child, "c2", child, "c3", child), namer);
    ensurePresent(mappings, "a", "c1", "a");
    ensurePresent(mappings, "a1", "c1", "a1");
    ensurePresent(mappings, "a_1", "c2", "a");
    ensurePresent(mappings, "a1_1", "c2", "a1");
    ensurePresent(mappings, "a_2", "c3", "a");
    ensurePresent(mappings, "a1_2", "c3", "a1");

  }

  private void ensurePresent(List<StructMapping> mappings, String key, String... segments) {
    StructMapping mapping = mappings.stream().filter(m -> key.equals(m.getKey())).findFirst().get();
    assertNotNull(mapping);
    for (int i = 0; i < segments.length; i++) {
      StructMember member = mapping.getSegments().get(i);
      assertNotNull(member);
      assertEquals(segments[i], member.getKey());
    }
  }

}
