/*
 * 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.net.URI;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.google.common.base.Strings;

import lombok.Getter;
import lombok.Setter;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Contains values to use when connecting to the PostGIS database.
 */
public class PostGISConnectionOptions {

  /**
   * URI scheme for RiskScape's postgis URIs
   */
  public static final String URI_SCHEME = "postgis";

  /**
   * Name of environment variable containing a password
   */
  public static final String ENV_PGPASSWORD = "PGPASSWORD";

  /**
   * Postgres listens on this port by default
   */
  public static final int DEFAULT_PSQL_PORT = 5432;

  /**
   * Parse the given location as a RiskScape specific-ish postgis URI.
   *
   * The given URI is expected to be of the form 'postgis://USER[:PASSWORD]@HOST[:PORT]/DATABASE'.  Any warnings from
   * parsing the URI are preserved for validation later.
   *
   * @param fromLocation to parse
   */
  public void setLocation(URI fromLocation) {
    this.location = fromLocation;
    if (!URI_SCHEME.equals(fromLocation.getScheme())) {
      throw new RuntimeException("Not a postgis uri " + fromLocation);
    }

    if (fromLocation.getPort() != -1) {
      // URI specifies a port, update with that
      port = fromLocation.getPort();
    }

    if (fromLocation.getHost() != null) {
      host = fromLocation.getHost();
    }

    String userInfo = fromLocation.getUserInfo();
    if (userInfo != null) {
      List<String> userParts = Arrays.asList(userInfo.split(":", 2));
      user = userParts.get(0);
      if (userParts.size() > 1) {
        password = userParts.get(1);
      }
    }

    String db = fromLocation.getPath();
    if (db != null && db.length() > 0) {
      // we remove any leading and/or trailing / from the path as that isn't part of the db name
      database = db.substring(1, db.length() - (db.endsWith("/") ? 1 : 0));
    }
  }

  public void setEnvironment(Map<String, String> env) {
    if (env.containsKey(ENV_PGPASSWORD)) {
      password = env.get(ENV_PGPASSWORD);
    }
  }

  /**
   * Validate this set of connection options, including any issues with the location (if specified)
   *
   * @return this options object, wrapped up with any warnings, if the options are good enough to generate a valid jdbc
   * uri.  Will return a failed result if there are missing fields.
   */
  public ResultOrProblems<PostGISConnectionOptions> validate() {
    List<Problem> problems = new LinkedList<>();

    if (location != null && location.getHost() == null && location.getUserInfo() == null && location.getPort() == -1) {
      // alpha characters where we expect the port to be messes up the parsing of the URI. in this case
      // we get nulls for host/userinfo, and the default -1 for port. So we detect this and bail with an invalid
      // location error rather than misleading missing host/user/database  errors
      // eg 'postgis://me@here:port/db'
      return ResultOrProblems.failed(PostGISProblems.get().invalidLocation(location));
    }

    if (Strings.isNullOrEmpty(host)) {
      problems.add(GeneralProblems.get().required("host"));
    }
    if (Strings.isNullOrEmpty(user)) {
      problems.add(GeneralProblems.get().required("user"));
    }
    if (Strings.isNullOrEmpty(database)) {
      problems.add(GeneralProblems.get().required("database"));
    }

    if (location != null) {

      if (Strings.isNullOrEmpty(location.getHost()) && !Strings.isNullOrEmpty(location.getSchemeSpecificPart())) {
        problems.add(PostGISProblems.get().ignoredFromLocation(location.getSchemeSpecificPart(), "uri suffix"));
      }
      if (location.getUserInfo() != null && location.getUserInfo().split(":", 2).length == 2) {
        problems.add(PostGISProblems.get().passwordInClearText());
      }
      if (location.getQuery() != null) {
        problems.add(PostGISProblems.get().ignoredFromLocation(location.getQuery(), "query"));
      }
      if (location.getFragment() != null) {
        problems.add(PostGISProblems.get().ignoredFromLocation(location.getFragment(), "fragment"));
      }
    }

    if (Problem.hasErrors(problems)) {
      return ResultOrProblems.failed(problems);
    } else {
      return ResultOrProblems.of(this, problems);
    }

  }

  @Getter
  private URI location;

  @Getter @Setter
  private String host;

  @Getter @Setter
  private int port = DEFAULT_PSQL_PORT;

  @Getter @Setter
  private String database;

  @Getter @Setter
  private String user;

  @Getter @Setter
  private String password;

  /**
   * @return a uri suitable for use with constructing a JDBC datasource.  Note that this might do terrible things if the
   * options are not valid.
   */
  public String toJdbcUri() {
    StringBuilder sb = new StringBuilder("jdbc:postgresql://");
    sb.append(host);
    sb.append(":").append(port);
    sb.append("/")
        .append(database)
        .append("?user=").append(user);
    if (password != null) {
      sb.append("&password=").append(password);
    }
    return sb.toString();
  }

  /**
   * Get a location URI that is broadly equivalent to point to the same DB. Exceptions are that the password
   * is never included, but the port is always included.
   */
  public URI toLocation() {
    String locationString = String.format("postgis://%s@%s:%d/%s", user, host, port, database);
    return URI.create(locationString);
  }

}
