package com.wecise.odb.jdbc;

import com.wecise.odb.Error;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.logging.Logger;

public class ODBDriver implements Driver {

    private final static String URL_PREFIX = "jdbc:wecise:omdb:";
    private final static String JDBC_DRIVER = "com.wecise.odb.jdbc.ODBDriver";

    @Override
    public Connection connect(String s, Properties properties) throws SQLException {
        String dbstr = s.substring(s.indexOf(URL_PREFIX) + URL_PREFIX.length());
        dbstr = dbstr.replaceAll("//", "");
        String[] a = dbstr.split("/");
        String address = "";
        String keyspace = "";
        if (a.length > 1) {
            address = a[0];
            keyspace = a[1];
        } else {
            throw new SQLException("Connect error, format: jdbc:wecise:omdb://<host:port>/<keyspace>");
        }
        return new ODBConnection(address, keyspace);
    }

    @Override
    public boolean acceptsURL(String s) throws SQLException {
        return s.startsWith(URL_PREFIX);
    }

    @Override
    public DriverPropertyInfo[] getPropertyInfo(String s, Properties properties) throws SQLException {
        return new DriverPropertyInfo[0];
    }

    @Override
    public int getMajorVersion() {
        return 1;
    }

    @Override
    public int getMinorVersion() {
        return 0;
    }

    @Override
    public boolean jdbcCompliant() {
        return false;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException(Error.methodNotSupported + ": Driver.getParentLogger()");
//        return null;
    }

    // This static block inits the driver when the class is loaded by the JVM.
    static {
        try {
            DriverManager.registerDriver(new ODBDriver());
        } catch (SQLException e) {
            throw new RuntimeException("Failed to initialize ODBJdbc driver: " + e.getMessage());
        }
    }
}
