package br.com.elotech.util;

import br.com.elotech.Main;
import br.com.elotech.config.ConnectionUtil;
import com.google.gson.Gson;
import org.httprpc.sql.Parameters;

import java.io.File;
import java.net.URISyntaxException;
import java.sql.*;
import java.util.Base64;

public abstract class Util {

    private static final Gson gson = new Gson();


    public static Object decodeArgsToJson(String arg, Class classe) {
        byte[] decoded = Base64.getMimeDecoder().decode(arg);
        return fromJsom(new String(decoded), classe);
    }

    public static Object fromJsom(String obj, Class classe) {
        return gson.fromJson(obj, classe);
    }


    public static String getJarPath() throws URISyntaxException {
        return new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
    }


    public static ResultSet resolveResultSet(String sql) throws SQLException {
        Parameters p = Parameters.parse(sql);
        Connection conn = ConnectionUtil.getConnection();
        PreparedStatement ps = conn.prepareStatement(p.getSQL());
        p.apply(ps);
        ResultSet rs = ps.executeQuery();
        conn.commit();
        conn.close();
        return rs;
    }
}
