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

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.junit.Test;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.hdf5.H5Dataset;
import nz.org.riskscape.hdf5.H5File;
import nz.org.riskscape.oq.events.EventMetadataLookup;

public class EventMetadataLookupIntegrationTest extends BaseHdf5Test {

  static final double TOLERANCE = 0.0000000001; // 10 decimal places

  H5File file = probabilisticFile();
  H5Dataset rupturesDataset = file.openDataset("/", "ruptures");
  H5Dataset eventsDataset = file.openDataset("/", "events");
  EventMetadataLookup metadataLookup = new EventMetadataLookup(eventsDataset, rupturesDataset);

  @Test
  public void canReadEventMetadata() throws Exception {
    // lookup an event at random and check we get the expected result
    Tuple result = (Tuple) metadataLookup.lookup(55L);
    // values from h5dumping /events
    assertThat(result.fetch("rup_id"), is(27L));
    // values from h5dumping /ruptures
    assertThat(result.fetch("rup_id"), is(27L));
    assertThat(result.fetch("source_id"), is("2864"));
    assertThat(result.fetch("n_occ"), is(2L));
    assertThat((Double) result.fetch("occurrence_rate"), closeTo(1.39748e-06, TOLERANCE));
    assertThat((Double) result.fetch("event_rate"), closeTo(1.39748e-06 / 2, TOLERANCE));
  }

  private HashMap<Long, Tuple> readAllEventMetadata(EventMetadataLookup lookupTable, long numEvents) {
    HashMap<Long, Tuple> results = new HashMap<>();

    for (long i = 0; i < numEvents; i++) {
      results.put(i, (Tuple) lookupTable.lookup(i));
    }
    return results;
  }

  private void validateEventMetadata(HashMap<Long, Tuple> metadata) {
    for (Tuple result : metadata.values()) {
      // rather than checking each individual value is correct, check that it's
      // within the range of values that we expect
      assertThat((Long) result.fetch("rup_id"), allOf(greaterThanOrEqualTo(0L), lessThanOrEqualTo(31L)));
      assertThat((String) result.fetch("source_id"), oneOf("2864", "21444", "21445"));
      long numOccurrences = (Long) result.fetch("n_occ");
      assertThat(numOccurrences, allOf(greaterThanOrEqualTo(2L), lessThanOrEqualTo(5L)));
      double occurrenceRate = (Double) result.fetch("occurrence_rate");
      assertThat(occurrenceRate,
          allOf(greaterThanOrEqualTo(8.94015613539522E-07), lessThanOrEqualTo(0.00062499998604)));
      assertThat((Double) result.fetch("event_rate"), closeTo(occurrenceRate / numOccurrences, TOLERANCE));
    }
  }

  @Test
  public void canReadAllEventMetadata() throws Exception {
    // read all the event metadat
    long numEvents = eventsDataset.getDataSpace().getExtent()[0];
    HashMap<Long, Tuple> results = readAllEventMetadata(metadataLookup, numEvents);

    // just validate that we got sane values back
    validateEventMetadata(results);
  }

  @Test
  public void canReadEventMetadataInParallel() throws Exception {
    // check we can read the event metadata from different threads without corruption
    long numEvents = eventsDataset.getDataSpace().getExtent()[0];
    List<HashMap<Long,Tuple>> results = new ArrayList<>();

    // run two threads in parallel that both try to read the same event metadata
    Thread t1 = new Thread(() -> {
      HashMap<Long,Tuple> data = readAllEventMetadata(metadataLookup, numEvents);
      synchronized (results) {
        results.add(data);
      }
    });
    Thread t2 = new Thread(() -> {
      HashMap<Long,Tuple> data = readAllEventMetadata(metadataLookup, numEvents);
      synchronized (results) {
        results.add(data);
      }
    });

    t1.start();
    t2.start();

    try {
      t1.join();
      t2.join();
    } catch (InterruptedException e) {
    }

    // validate that we got sane values back
    validateEventMetadata(results.get(0));
    validateEventMetadata(results.get(1));

    // both threads should produce the exact same results
    assertEquals(results.get(0), results.get(1));
  }
}
