package org.bdware.sc.contractexample;

import com.google.gson.JsonObject;
import org.bdware.sc.boundry.utils.RocksDBUtil;
import org.bdware.sc.boundry.utils.SQLUtil;
import org.rocksdb.RocksIterator;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.sql.Connection;

public class Storage {
    static {
        SQLUtil.initDriver("org.postgresql.Driver");
    }

    public static Storage instance = new Storage();
    public RocksDBUtil grsStorage = RocksDBUtil.loadDB("./grsTable", false);
    Connection conn;

    public Connection getDBConnection() {
        ResolveConfig resolveConfig = Resolver.getConfig();
        try {
            if (instance.conn != null && instance.conn.isValid(2)) {
                return instance.conn;
            }
            instance.conn = SQLUtil.getConnection(resolveConfig.dbUrl, resolveConfig.dbUserName, resolveConfig.dbPwd);
            return instance.conn;
        } catch (Exception e) {
            instance.conn = SQLUtil.getConnection(resolveConfig.dbUrl, resolveConfig.dbUserName, resolveConfig.dbPwd);
            return instance.conn;
        }
    }

    public JsonObject peekDB() {
        RocksIterator iter = grsStorage.newIterator();
        JsonObject ret = new JsonObject();
        try {
            for (iter.seekToFirst(); iter.isValid(); iter.next()) {
                String jsonStr = new String(iter.value());
                ret.addProperty(new String(iter.key()), jsonStr);
            }
        } catch (Exception e) {
            ret.addProperty("result", "failed");
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(bo));
            ret.addProperty("errorMessage", bo.toString());
        }
        return ret;
    }
}
