/*
 * Created with IntelliJ IDEA.
 * User: michaelpotter
 * Date: 30/03/15
 * Time: 11:45
 */
package io.github.mvpotter.data.configuration;

import io.github.mvpotter.data.configuration.support.DBProfile;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import javax.sql.DataSource;
import java.net.URI;
import java.net.URISyntaxException;

@Configuration
@Profile(DBProfile.POSTGRES)
public class PostgresConfig {

    public static final String ENV_DATABASE_KEY = "database.url";
    public static final String POSTGRES_DRIVER = "org.postgresql.Driver";

    private static final String URL_FORMAT = "jdbc:postgresql://%s%s";

    @Bean
    public DataSource dataSource() throws URISyntaxException {
        String dbProperty = System.getProperty(ENV_DATABASE_KEY);
        if(dbProperty != null) {
            final URI uri = new URI(dbProperty);
            final String[] credentials = uri.getUserInfo().split(":");
            final String username = credentials[0];
            String password = "";
            if (credentials.length > 1) {
                password = credentials[1];
            }
            final String url = String.format(URL_FORMAT, uri.getHost(), uri.getPath());

            return DataSourceBuilder.create()
                    .driverClassName(POSTGRES_DRIVER)
                    .url(url)
                    .username(username)
                    .password(password)
                    .build();
        }

        throw new IllegalStateException("Unable to create data source");

    }

}

@@ -655,20 +655,20 @@
  = %22
-database.url
+DATABASE_URL
 %22;%0A 
@@ -807,16 +807,19 @@
 sql://%25s
+:%25s
 %25s%22;%0A%0A  
@@ -927,24 +927,19 @@
 stem.get
-Property
+env
 (ENV_DAT
@@ -1359,16 +1359,31 @@
 tHost(),
+ uri.getPort(),
  uri.get

Fix issue with getting heroku postgres settings