package org.bdware.sc.db;

import org.bdware.sc.commParser.BlockBody;
import org.bdware.sc.util.HashUtil;

import java.io.File;
import java.sql.*;

public class SqliteDBUtil {
    private Connection conn;

    public static SqliteDBUtil connect(String url) {
        try {
            String name = "org.sqlite.JDBC";
            SqliteDBUtil util = new SqliteDBUtil();
            String path = "jdbc:sqlite:";
            File file = new File(url);
            path = path + file.getAbsolutePath();
            System.out.println("[SqliteDBUtil] connect:" + path);
            Class.forName(name);
            util.conn = DriverManager.getConnection(path);
            return util;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public BlockBody getBlockBody(String headerHash, String bodyHash) {
        try {
            Statement stmt = conn.createStatement();
            // ResultSet result = stmt.executeQuery("select * from BlockHeader where hash =
            // " + headerHash);
            String sql = "select * from BlockBody where ID = ?";
            PreparedStatement pre = conn.prepareStatement(sql);
            pre.setBytes(1, HashUtil.str16ToBytes(bodyHash));
            ResultSet result = pre.executeQuery();
            // Assert we get only one!!!!
            result.next();
            System.out.println(result.getBytes("ID"));
            return BlockBody.fromBytes(result.getBytes("Data"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public byte[] selectAll() {
        try {
            Statement stmt = conn.createStatement();
            // ResultSet result = stmt.executeQuery("select * from BlockHeader where hash =
            // " + headerHash);
            String sql = "select * from BlockBody limit 0,1";
            PreparedStatement pre = conn.prepareStatement(sql);
            ResultSet result = pre.executeQuery();
            // Assert we get only one!!!!
            result.next();
            return result.getBytes(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
