/**
 * @author (c) April 2018 Michael Ziemke
 * @version v1.1 27.04.2018
 */
public class DBTest
{
    // Objektvariablen der Bezugsobjekte

    // Attribute (Instanzvariablen)
    private String ip = "85.13.155.185";  // Datenbanken bei All-Inkl.com für landrat-lucas.org
    private int port  = 3306;
    private String dbName = "d02a3ccc"; // KT-LEV-FOBI
    private String dbLogin = "d02a3ccc";
    private String dbPassword = "KT-LEV-FOBI2018";
    private DatabaseConnector con;  // nimmt das Datenbank-Handle nach dem Verbinden auf
    private QueryResult res;  // nimmt die durch SQL-Abfrage erhaltene Ressource auf
    private String tableName = "dbtest";

    // Konstruktor
    public DBTest()
    { 
      this.erzeugeTabelle();    
      this.fuegeDatenHinzu();
      this.zeigeNamen();
      this.loescheDaten(3,999);
      this.zeigeNamen();
      if (InOut.readBoolean("\nAbschließend Tabelle wieder löschen (j/n) ? ")) this.loescheTabelle();
    }
  
    private boolean verbinde () {
        // Verbindung herstellen:
        //System.out.println("Start des DB-Connect:");
        this.con = new DatabaseConnector(this.ip, this.port, this.dbName, this.dbLogin, this.dbPassword);
        if (this.con == null) {
            System.out.println("Kein DB-Connect möglich!");
            return false;
        } else {
          // System.out.println("DB-Connect-Handle ist: " + this.con);
        } // end of if-else
        if (zeigeFehler(true)) return false;
        return true;
    }
  
    private void erzeugeTabelle() {
      String sql = "CREATE TABLE IF NOT EXISTS `" + this.tableName + "` ("
       + "`id` int(5) NOT NULL AUTO_INCREMENT,"
       + "`nachname` varchar(20) NOT NULL,"
       + "`vorname` varchar(20) NOT NULL,"
       + "  PRIMARY KEY (`id`)"
       + ") ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Test-Tabelle' AUTO_INCREMENT=1 ;"
       ;
      if (!verbinde()) return;
      System.out.println("\nSQL-Statement ist:\n" + sql);
      this.con.executeStatement(sql);
      if (!zeigeFehler(false)) {
        System.out.println("Tabelle wurde erfolgreich erzeugt.");
      } else {
        System.out.println("FEHLER: Tabelle wurde nicht erzeugt.");
      } // end of if-else
      this.con.close();
    }
     
    private void fuegeDatenHinzu() {
      String sql = "INSERT INTO `" + this.dbName + "`.`" + this.tableName + "` "
        + " (`nachname`, `vorname`) VALUES ('Duck', 'Donald'), ('Gans', 'Gustav');"
        ;
      if (!verbinde()) return;
      System.out.println("\nSQL-Statement ist:\n" + sql);
      this.con.executeStatement(sql);
      if (!zeigeFehler(false)) {
        System.out.println("Tabelle wurde erfolgreich mit Daten gefüllt.");
      } else {
        System.out.println("FEHLER: Tabelle wurde nicht mit Daten gefüllt.");
      } // end of if-else
      this.con.close();
    }

    private boolean zeigeFehler (boolean pSchliesse) {
      boolean ret = false;
      if (this.con.getErrorMessage() != null) {
        ret = true;
        System.out.println("Fehler: " + this.con.getErrorMessage());
        if (pSchliesse) this.con.close();
      }
      return ret;
    }
  
    private void loescheDaten (int pVonId, int pBisId) {
      String sql = "DELETE FROM `" + this.tableName+ "` WHERE id>=" + pVonId + " AND id<=" + pBisId +";";  
      if (!verbinde()) return;
      System.out.println("\nSQL-Statement ist:\n" + sql);
      this.con.executeStatement(sql);
      if (!zeigeFehler(false)) {
        System.out.println("Tabellendaten von ID=" + pVonId + " bis ID=" + pBisId + " wurden erfolgreich gelöscht.");
      } else {
        System.out.println("FEHLER: Tabellendaten konnten nicht gelöscht werden.");
      } // end of if-else
      this.con.close();
    }
  
    private void loescheTabelle() {
      String sql = "DROP TABLE IF EXISTS `" + this.tableName+ "`;";  
      if (!verbinde()) return;
      System.out.println("\nSQL-Statement ist:\n" + sql);
      this.con.executeStatement(sql);
      if (!zeigeFehler(false)) {
        System.out.println("Tabellen wurde erfolgreich gelöscht.");
      } else {
        System.out.println("FEHLER: Tabelle konnten nicht gelöscht werden.");
      } // end of if-else
      this.con.close();
    }
  
    public void zeigeNamen() {
      String sql = "SELECT nachname,vorname FROM `" + this.tableName + "`";
      if (!verbinde()) return;
      System.out.println("\nSQL-Statement ist:\n" + sql);
      this.con.executeStatement(sql);
      this.res = this.con.getCurrentQueryResult();
      if (this.res != null) {
        System.out.println("Nachname \tVorname");
        for (int i = 0; i < this.res.getRowCount(); i++) {
          System.out.print(this.res.getData()[i][0]+"\t");
          System.out.println(this.res.getData()[i][1]);
        }
      } else {
        System.out.println(this.con.getErrorMessage());
      }
      this.con.close();
    }

    public void testeAllgemeineAnfrage(String pAnfrage) {
        if (!verbinde()) return;
        this.con.executeStatement(pAnfrage);
        this.res = con.getCurrentQueryResult();
        if (this.res != null) {
            for (int i = 0; i < res.getColumnCount(); i++) {
                System.out.print(this.res.getColumnNames()[i]+"\t");
            }
            System.out.println();
            for (int j = 0; j < this.res.getRowCount(); j++) {
                for (int i = 0; i < this.res.getColumnCount(); i++) {
                    System.out.print(this.res.getData()[j][i]+"\t");
                }
                System.out.println();
            }
        } else {
            System.out.println(this.con.getErrorMessage());
        }
        this.con.close();
    }

    public static void main(String[] args) {
        new DBTest();
    }
}
