/*
 * 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.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;

import com.google.common.collect.ImmutableMap;

import lombok.extern.slf4j.Slf4j;
import nz.org.riskscape.engine.SRIDSet;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.data.relation.LockDefeater;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.engine.types.Value;
import nz.org.riskscape.problem.ProblemSink;

/**
 * Writes typed riskscape {@link Value}s out to a new shapefile.
 * <p>
 * Due to restrictions in the shapefile format and geotools' own hacks to work with them, the {@link ShapefileWriter}
 * writes out the geometry to the <code>the_geom</code> magic feature attribute.  If geometry also appears in the
 * value, the writer either ignores it (if it was also passed as the special geometry parameter) or writes it out as
 * text in WKT
 */
@Slf4j
public class ShapefileWriter extends AbstractDataStoreWriter {

  /**
   * Needed for constructing shapefile data stores
   * NB unsure of thread safety
   */
  public static final ShapefileDataStoreFactory FACTORY = new ShapefileDataStoreFactory();
  public static final int MAX_FIELD_LENGTH = 10;
  private static final LockDefeater LOCK_DEFEATER = new LockDefeater("ShapefileWriter_geotools");

  private final ShapeFileNullMapper nullMapper = new ShapeFileNullMapper();

  private final ProblemSink problemSink;

  public ShapefileWriter(File outfile, SRIDSet sridSet, ProblemSink problemSink) throws IOException {
    super(outfile, sridSet,
    FACTORY.createNewDataStore(ImmutableMap.of(
        "url", outfile.toURI().toURL(),
        "create spatial index", Boolean.TRUE)));
    this.problemSink = problemSink;
  }

  @Override
  public void close() throws IOException {
    LOCK_DEFEATER.call("close datastore", () -> {
      super.close();
      return true;
    });
  }

  @Override
  protected int getAttrNameMaxLength() {
    return MAX_FIELD_LENGTH;
  }

  @Override
  protected CoordinateReferenceSystem outputCrs(CoordinateReferenceSystem crs) {
    axisSwapper = AxisSwapper.getForceXY(crs, getStoredAt(), problemSink).orElse(null);
    return super.outputCrs(axisSwapper == null ? crs : axisSwapper.getNewCrs());
  }

  @Override
  protected void setupCrsAndGeoType(Tuple value) throws IOException {
    if (this.setup) {
      return;
    }

    LOCK_DEFEATER.call("setup CRS and geom type", () -> {
      super.setupCrsAndGeoType(value);
      return true;
    });

    List<String> nullables = this.mappings.stream()
        .filter(m -> Nullable.is(m.getType()))
        .map(m -> m.getKey())
        .collect(Collectors.toList());
    if (! nullables.isEmpty()) {
      log.warn("Entries in {} will contain mapped values should the actual value be null", nullables);
    }
  }

  @Override
  protected Object mapValueIfNecessary(Object value, Type type) {
    return nullMapper.mapValueIfNecessary(value, type);
  }

}
