package main.java;

import java.sql.Connection;
import java.sql.SQLException;

public class DbConnection {
    private static Connection connection;

    public static void setConnection(Connection connection){
        if (connection == null)
            throw new NullPointerException("Invalid connection: Null");
        DbConnection.connection = connection;
    }

    public static Connection getCon() {
        if (connection == null)
            throw new NullPointerException("Invalid connection: Not set");
        return connection;
    }

    public static void setAutoCommit (boolean val){
        try {
            connection.setAutoCommit(val);
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    public static void rollback() {
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void setIsolation (int val) {
        try {
            connection.setTransactionIsolation(val);
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    public static void disableCommit () {
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    public static void resetCommit () {
        try {
            connection.setAutoCommit(true);
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    public static void setIsolationCommitted () {
        try {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    public static void resetIsolation (){
        try {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    public static void clear() {connection = null;}
}
