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

import org.geotools.geopkg.RsGeoPkgDialect;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

import org.geotools.geopkg.GeoPkgDataStoreFactory;
import org.geotools.geopkg.geom.GeoPkgGeomWriter;
import org.geotools.jdbc.JDBCDataStore;
import org.geotools.jdbc.SQLDialect;

import lombok.Setter;

/**
 * Extends the base geopackage data store to fix:
 * - riskscape#1291 (geopackage on readonly filesystems)
 * - riskscape#1571 (curved geometry support)
 */
public class RsGpkgDataStoreFactory extends GeoPkgDataStoreFactory {

  /*
   * We can't use the original method at all, because it throws away the file: part of the protocol. Without that,
   * the sqlite connection gets confused about the path and thinks the database doesn't exist
   */
  @Override
  protected String getJDBCUrl(Map<String, ?> params) throws IOException {
    String database = params.get("database").toString();
    Path databasePath = Paths.get(database);

    StringBuilder url = new StringBuilder();
    // NB it's key that the `file:` component be here
    url.append("jdbc:sqlite:file:");
    url.append(database.toString());

    // If someone has saved a gpkg that's still in the middle of a transaction, it'll be in 'wal-mode' and sqlite will
    // try to recover from the transactionm, even if the database is read only.  If this file is being accessed via a
    // read only file system (such as rclone-fuse on a platform managed engine) then sqlite will fail to open the
    // database because it can't repair it.  To work around this, sqlite has this extra concept of opening it in
    // immutable mode, which will recover the database, but won't try and write that out anywhere.  This fixes
    // riskscape#1291
    if (isNeedImmutable(databasePath)) {
      // This is the important bit - https://www.sqlite.org/wal.html#readonly
      url.append("?immutable=true");
    }

    return url.toString();
 }

  boolean isNeedImmutable(Path databasePath) {
    // it's interesting to note that if you `ls -l` a fuse mounted platform storage, the directories and files look
    // writable, but these java APIs are still showing that you can't write to them , which is good as it means we don't
    // need to probe the dir by touching an empty file
    return Files.exists(databasePath)
        && !Files.isWritable(databasePath.getParent())
        && !Files.isWritable(databasePath);
  }

  // CURVE GEOMETRY support
  @Setter
  private boolean enableCurvedGeometrySupport = false;

  // Adds support for curved geometries. When Geotools is updated to a version that included GEOT-7834
  // this method can be removed along with RsGeoPkgDialect and related classes.
  @Override
  protected SQLDialect createSQLDialect(JDBCDataStore dataStore) {
    if (enableCurvedGeometrySupport) {
      // for now we only enable the RsGeoPkgDialect (which adds support for curved geometries) when
      // the user has request this support.
      return new RsGeoPkgDialect(dataStore, new GeoPkgGeomWriter.Configuration());
    }
    // no curved geometry support then use the defaults
    return super.createSQLDialect(dataStore);
  }

}
