package me.km.databank;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import me.km.api.Module;
import net.minecraft.util.text.TextFormatting;

public class DataBank extends Module
{
    private Connection c;
    private final String user;
    private final String password;
    
    public DataBank(String mname, String prefix, TextFormatting color, String user, String password) 
    {
        super(mname, prefix, color);
        this.user = user;
        this.password = password;
    }
    
    public boolean openDataBankConnection()
    {
        c = null;
        try 
        {
            // The newInstance() call is a work around for some broken Java implementations
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            c = DriverManager.getConnection("jdbc:mysql://localhost/minecraft?autoReconnect=true", user, password);
            this.sendToConsole("Die Verbindung wurde erfolgreich aufgebaut.");
            return true;
        } 
        catch(ClassNotFoundException | IllegalAccessException | InstantiationException | SQLException ex) 
        {
            this.sendWarningToConsole(ex.toString());
            return false;
        }
    }
    
    public void closeDataBankConnection()
    {
        try 
        {
            c.close();
            this.sendToConsole("Die Verbindung wurde erfolgreich unterbrochen.");
        } 
        catch (SQLException ex) 
        {
            this.sendWarningToConsole(ex.getMessage());
        }
        catch (NullPointerException ex) 
        {
        }
    }
    
    public Connection getConnection()
    {
        /*try 
        {
            if(c.isClosed())
            {
                openDataBankConnection();
            }
        }
        catch(SQLException ex) 
        {
        }*/
        return c;
    } 
}