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

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import org.geotools.api.data.DataAccessFactory.Param;
import org.geotools.data.postgis.PostgisNGDataStoreFactory;
import org.geotools.api.data.SimpleFeatureSource;
import org.geotools.jdbc.JDBCDataStore;
import org.geotools.jdbc.JDBCDataStoreFactory;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import lombok.Getter;

import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.ParameterField;
import nz.org.riskscape.engine.data.Bookmark;
import nz.org.riskscape.engine.data.relation.FeatureSourceBookmarkResolver;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;

public class PostGISResolver extends FeatureSourceBookmarkResolver<JDBCDataStore, PostGISResolver.Params> {

  public static final String FORMAT = "postgis";

  public static final PostgisNGDataStoreFactory FACTORY = new PostgisNGDataStoreFactory();

  private static final PostGISProblems POSTGIS_PROBLEMS = PostGISProblems.get();

  public static class Params extends FeatureSourceBookmarkParams {

    @ParameterField()
    public Optional<String> user = Optional.empty();

    @ParameterField()
    public Optional<String> password = Optional.empty();

    @ParameterField()
    public Optional<String> database = Optional.empty();

    @ParameterField()
    public Optional<Integer> port = Optional.empty();

    // gets populated during validation - these get given to the geotools code to set up a connection
    public Map<String, Object> storeParams = Maps.newHashMap();

    // gets populated during validation, kept here for use if DB connection fails
    public final PostGISConnectionOptions connectionOptions = new PostGISConnectionOptions();

    void populateConnectionOptions() {
      // set options from uri first
      connectionOptions.setLocation(getLocation());
      // look for pgpassword
      connectionOptions.setEnvironment(System.getenv());

      // bookmark specified things win
      user.ifPresent(u -> connectionOptions.setUser(u));
      password.ifPresent(p -> connectionOptions.setPassword(p));
      database.ifPresent(d -> connectionOptions.setDatabase(d));
      port.ifPresent(p -> connectionOptions.setPort(p));
    }
  }

  public PostGISResolver(Engine engine) {
    super(engine);
  }

  @Getter
  private final Map<String, String> aliasMapping = ImmutableMap.of("passwd", "password");

  @Override
  protected JDBCDataStore createDataStore(Params params)
      throws MalformedURLException, IOException {

    try {
      return FACTORY.createDataStore(params.storeParams);
    } catch (Exception e) {
      // We have not been able to connect to the PostGIS data source. We wrap this up in a custom problem
      // with tips to help the user fix it up.
      throw new RiskscapeException(
          PostGISPipelineOutputStore.toConnectionFailure(params.connectionOptions.toLocation(), e)
      );
    }
  }

  @Override
  protected ResultOrProblems<SimpleFeatureSource> createFeatureSource(Params params, JDBCDataStore dataStore) {
    try {
      return super.createFeatureSource(params, dataStore);
    } catch (Exception e) {
      // We have not been able to connect to the PostGIS data source. We wrap this up in a custom problem
      // with tips to help the user fix it up.
      return ResultOrProblems.failed(
          PostGISPipelineOutputStore.toConnectionFailure(params.connectionOptions.toLocation(), e)
      );
    }
  }

  @Override
  protected void validateParameters(Params params, BindingContext context) {
    super.validateParameters(params, context);
    params.populateConnectionOptions();

    params.connectionOptions.validate().ifElse(
      opt -> {
        Map<String, Object> storeParams = params.storeParams;
        storeParams.put(JDBCDataStoreFactory.DBTYPE.key, PostgisNGDataStoreFactory.DBTYPE.getDefaultValue());

        storeParams.put(JDBCDataStoreFactory.HOST.key, opt.getHost());
        storeParams.put(JDBCDataStoreFactory.PORT.key, opt.getPort());
        storeParams.put(JDBCDataStoreFactory.DATABASE.key, opt.getDatabase());
        storeParams.put(JDBCDataStoreFactory.USER.key, opt.getUser());

        if (!Strings.isNullOrEmpty(opt.getPassword())) {
          storeParams.put(JDBCDataStoreFactory.PASSWD.key, opt.getPassword());
        }
        // most of these should have already been validated by the postgisconnection options class, but this does a
        // second check according to what the postgis geotools code wants to see
        List<Param> factoryParams = Arrays.asList(FACTORY.getParametersInfo());
        for (Param param : factoryParams) {
          Object storeParamValue = storeParams.get(param.key);
          String storeParam = storeParamValue == null ? null : storeParamValue.toString();

          if (Strings.isNullOrEmpty(storeParam)) {
            if (param.isRequired()) {
              params.add(Problem.error("'%s' is a required parameter for PostGIS bookmarks.  Parameters"
                  + " can also be set via the location, e.g. postgis://user:password@host:port/database", param.key));
            }
          }
        }
      },
      problems -> params.problems.addAll(problems)
    );

  }

  @Override
  public String getFormat(Bookmark bookmark) {
    if (Strings.isNullOrEmpty(bookmark.getFormat())) {
      if (FORMAT.equals(bookmark.getLocation().getScheme())) {
        return FORMAT;
      }
    }

    return bookmark.getFormat();
  }

  @Override
  protected Map<String, String> getExtensionsToFormats() {
    return Collections.emptyMap();
  }

  @Override
  public Set<String> getFormats() {
    return Collections.singleton(FORMAT);
  }
}
