/*
 * Copyright (C) 2013 Rappold <http://wyrez.org> and contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.wyrez.shootingstars.io;

/**
 *
 * @author Rappold
 */
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLiteConnector {

    private static final String DB_PATH = "scoresdb.db";

    public SQLiteConnector() {
    }

    public Connection initDBConnection() {
        Connection connection = null;
        boolean newFile = false;
        try {
            Class.forName("org.sqlite.JDBC");

            String sqliteTable = "CREATE TABLE Scores (Name VARCHAR(250), Points INT(20), SongName VARCHAR(250), GameDate DATE)";
            File sQLiteDb = new File(DB_PATH);
            if (!sQLiteDb.exists()) {
                    sQLiteDb.createNewFile();
                    newFile = true;
            }

            connection = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
            
            if(newFile) {
                Statement stmt = connection.createStatement();
                stmt.executeUpdate(sqliteTable);
            }
            return connection;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public ResultSet excecuteQuery(Connection con, String query) {
        ResultSet result = null;
        try {
            Statement stmt = con.createStatement();
            result = stmt.executeQuery(query);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public int excecuteUpdate(Connection con, String query) {
        int result = 0;
        try {
            Statement stmt = con.createStatement();
            result = stmt.executeUpdate(query);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
}