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

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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import org.junit.Test;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.data.InputDataProblems;
import nz.org.riskscape.engine.query.TupleUtils;
import nz.org.riskscape.engine.relation.UnexpectedNullValueException;
import nz.org.riskscape.engine.types.Struct.StructBuilder;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.problem.ResultOrProblems;

public class StructTest {

  Struct underTest = Struct.of("foo", Types.TEXT);

  @Test
  public void willCoerceToATuple() {
    Tuple coerced = (Tuple) underTest.coerce(ImmutableMap.of("foo", "bar"));
    assertEquals(ImmutableMap.of("foo", "bar"), coerced.toMap());

    coerced = (Tuple) underTest.coerce(new Tuple(underTest).set("foo", "bar"));
    assertEquals(new Tuple(underTest).set("foo", "bar"), coerced);
  }

  @Test
  public void canCoerceFromSingleValueToSingleEntryStruct() {
    Tuple coercedMap = (Tuple) underTest.coerce("bar");
    assertEquals(ImmutableMap.of("foo", "bar"), coercedMap.toMap());
  }

  @Test
  public void canCoerceFromSingleNullValueToSingleEntryStructIfNullableType() {
    underTest = Struct.of("foo", Nullable.TEXT);

    Tuple coerced = (Tuple)underTest.coerce(null);
    assertNull(coerced.fetch("foo"));
  }

  @Test(expected=CoercionException.class)
  public void cannotCoerceFromSingleNullValueToSingleEntryStruct() {
    underTest.coerce(null);
  }

  @Test
  public void willNotCoerceATupleOfTheDesiredType() throws Exception {
    Tuple tuple = Tuple.ofValues(underTest, 1L);
    assertSame(tuple, underTest.coerce(tuple));

    assertEquals(Long.valueOf(1L), tuple.fetch("foo"));
  }

  @Test
  public void willCoerceAnEquivalentButNotSameTupleOfTheDesiredType() throws Exception {
    Struct similar = Struct.of("foo", Types.TEXT);
    Tuple tuple = Tuple.ofValues(underTest, 1L);
    Tuple coerced = (Tuple) similar.coerce(tuple);
    assertNotSame(tuple, coerced);
    assertEquals("1", coerced.fetch("foo"));
  }

  @Test
  public void builderCanBeUsedToProduceManyTypes() throws Exception {
    // join code relies on this behaviour to progressively build the joined type
    StructBuilder builder = Struct.builder();

    Struct a = builder.add("a", Types.TEXT).build();
    Struct b = builder.add("b", Types.TEXT).build();
    Struct c = builder.add("c", Types.TEXT).build();

    assertEquals(Struct.of("a", Types.TEXT), a);
    assertEquals(Struct.of("a", Types.TEXT, "b", Types.TEXT), b);
    assertEquals(Struct.of("a", Types.TEXT, "b", Types.TEXT, "c", Types.TEXT), c);
  }

  @Test
  public void builderAddAllAppendsAllOfAnotherStructsMembers() throws Exception {
    StructBuilder builder = Struct.builder();

    Struct addAllOfThis = Struct.of("foo-1", Types.FLOATING, "foo-2", Types.DECIMAL);

    builder.add("bar", Types.TEXT);
    builder.addAll(addAllOfThis);
    builder.add("baz", Types.GEOMETRY);

    Struct expected = Struct
        .of("bar", Types.TEXT)
        .and("foo-1", Types.FLOATING)
        .and("foo-2", Types.DECIMAL)
        .and("baz", Types.GEOMETRY);

    assertEquals(expected, builder.build());
  }

  @Test(expected = DuplicateKeysException.class)
  public void duplicateMembersThrowsDuplicateKeysException() throws Exception {
    Struct.of("foo", Types.TEXT, "foo", Types.TEXT);
  }

  @Test
  public void builderCanReturnAResultOrProblemsWithDupesReportedAsProblems() throws Exception {
    StructBuilder builder = Struct.builder();

    builder.add("foo", Types.TEXT);
    builder.add("bar", Types.TEXT);
    builder.add("baz", Types.TEXT);

    builder.add("foo", Types.TEXT);

    ResultOrProblems<Struct> structOr = builder.buildOr();
    assertTrue(structOr.hasErrors());

    assertThat(structOr.getProblems(), contains(
        equalTo(TypeProblems.get().duplicateKeys(
            Sets.newHashSet(new StructMember("foo", Types.TEXT, 0), new StructMember("foo", Types.TEXT, 3))
          ))
    ));
  }

  @Test
  public void canReplaceAMember() throws Exception {
    Struct struct = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER, "baz", Types.FLOATING);
    assertEquals(
        Struct.of("foo", Types.TEXT, "bar", Types.GEOMETRY, "baz", Types.FLOATING),
        struct.replace("bar", Types.GEOMETRY));
  }

  @Test(expected=IllegalArgumentException.class)
  public void replacingANonExistantMemberThrows() throws Exception {
    Struct.of("foo", Types.TEXT, "bar", Types.INTEGER, "baz", Types.FLOATING).replace("boz", Types.GEOMETRY);
  }

  @Test
  public void addOrReplaceWorksForExistingOrNot() throws Exception {
    assertEquals(
        Struct.of("foo", Types.INTEGER),
        Struct.of().addOrReplace("foo", Types.TEXT).addOrReplace("foo", Types.INTEGER)
    );
  }

  @Test
  public void getMemberReturnsEmptyForMissingMember() throws Exception {
    assertFalse(Struct.of("foo", Types.TEXT).getMember("bar").isPresent());
  }

  @Test
  public void getMemberReturnsByName() throws Exception {
    StructMember member = Struct.of("foo", Types.TEXT).getMember("foo").get();
    assertEquals("foo", member.getKey());
    assertEquals(0, member.getIndex());
    assertEquals(Types.TEXT, member.getType());
  }

  @Test
  public void canCreateAnEmptyStruct() throws Exception {
    Struct empty = Struct.of();
    assertEquals(0, empty.size());
    assertSame(empty, Struct.of());
  }

  @Test
  public void canSerializeStruct() throws Exception {
    Struct struct = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER, "baz", Types.FLOATING);
    Tuple value = Tuple.ofValues(struct, "one", 2L, 3.0D);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    struct.toBytes(dos, value);
    assertEquals(value, struct.fromBytes(new DataInputStream(new ByteArrayInputStream(bos.toByteArray()))));
  }

  @Test
  public void getSaneErrorIfNullValueSerialized() throws Exception {
    Struct struct = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER, "whoops", Types.FLOATING);
    Tuple value = Tuple.ofValues(struct, "one", 2, null);
    DataOutputStream dos = new DataOutputStream(new ByteArrayOutputStream());
    try {
      struct.toBytes(dos, value);
      fail("Should have raised an exception");
    } catch (UnexpectedNullValueException ex) {
      assertEquals(ex.getProblem(),
          InputDataProblems.get().unexpectedNullValue("whoops", TupleUtils.getContentSummary(value))
      );
    } catch (Throwable t) {
      fail("Should have raised a UnexpectedNullValueException");
    }
  }

  @Test
  public void canReadWriteBytesFromSameStruct() {
    Struct fooBar = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER);

    Tuple toWrite = Tuple.ofValues(fooBar, "foo", 33L);

    assertThat(writeThenRead(fooBar, toWrite), allOf(
        equalTo(toWrite),
        not(sameInstance(toWrite)),
        hasProperty("struct", sameInstance(fooBar))
    ));
  }

  @Test
  public void canReadWriteBytesFromEqualStruct() {
    Struct fooBar1 = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER);
    Struct fooBar2 = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER);

    //sanity checks
    assertThat(fooBar1, equalTo(fooBar2));
    assertThat(fooBar1, not(sameInstance(fooBar2)));

    Tuple toWrite = Tuple.ofValues(fooBar2, "foo", 33L);

    assertThat(writeThenRead(fooBar1, toWrite), allOf(
        equalTo(Tuple.ofValues(fooBar1, "foo", 33L)),
        hasProperty("struct", sameInstance(fooBar1))
    ));
  }

  @Test
  public void cannotWriteBytesFromDifferentStruct() {
    Struct fooBar = Struct.of("foo", Types.TEXT, "bar", Types.INTEGER);

    // replace the bar type
    Tuple toWrite = Tuple.ofValues(fooBar.replace("bar", Types.FLOATING), "foo", 33.5D);
    try {
      writeThenRead(fooBar, toWrite);
      fail();
    } catch (AssertionError ae) {}

    // an added member
    toWrite = Tuple.ofValues(fooBar.add("baz", Types.TEXT), "foo", 33L, "baz");
    try {
      writeThenRead(fooBar, toWrite);
      fail();
    } catch (AssertionError ae) {}
  }

  /**
   * Writes the given tuple as the given struct type. Then reads it back.
   */
  private Tuple writeThenRead(Struct toWriteAs, Tuple toWrite) {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos)) {
      toWriteAs.toBytes(dos, toWrite);
      dos.flush();

      try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
          DataInputStream dis = new DataInputStream(bis)) {
        return (Tuple)toWriteAs.fromBytes(dis);
      }
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }
  }

}
