package testes.sefaz.sat;

import java.util.Map;
import java.util.TreeMap;

public class SATRequest {

    private final String baseURL;

    public static void main(String[] args) throws Exception {
        System.out.println("--INICIO--");
        SATRequest sat = new SATRequest("http://127.0.0.1:47407");
        System.out.println(sat.consultarStatusOperacional("123", ""));
        System.out.println("--FIM--");
    }

    private String gerarCodigoVinculacao(String conectorV, String cnpjDesenvolvedor, String cnpjEstabelecimento) throws Exception {
        Map<String, String> paramsValues = new TreeMap<String, String>();
        paramsValues.put("conectorV", conectorV);
        paramsValues.put("cnpjDesenvolvedor", cnpjDesenvolvedor);
        paramsValues.put("cnpjEstabelecimento", cnpjEstabelecimento);
        return remoteCall("l2sSEFAZGerarCodigoVinculacao", paramsValues);
    }

    private String consultarStatusOperacional(String numeroSessao, String codigoDeAtivacao) throws Exception {
        Map<String, String> paramsValues = new TreeMap<String, String>();
        paramsValues.put("numeroSessao", numeroSessao);
        paramsValues.put("codigoDeAtivacao", codigoDeAtivacao);
        return remoteCall("l2sSEFAZSATConsultarStatusOperacional", paramsValues);
    }

    private String testeFimAFim(String numeroSessao, String codigoDeAtivacao, String dadosVenda) throws Exception {
        Map<String, String> paramsValues = new TreeMap<String, String>();
        paramsValues.put("numeroSessao", numeroSessao);
        paramsValues.put("codigoDeAtivacao", codigoDeAtivacao);
        paramsValues.put("dadosVenda", dadosVenda);
        return remoteCall("l2sSEFAZSATTesteFimAFim", paramsValues);
    }

    public SATRequest(String server) {
        this.baseURL = server + "/func/";
    }

    private final String remoteCall(String funcName, Map<String, String> paramsValues)
            throws Exception {
        // Variant chaveAPIVar, Variant usuarioNomeVar, Variant numeroTelVar,
        // Variant mensTextoVar
        StringBuffer postData = new StringBuffer();
        for(Map.Entry<String, String> pItem: paramsValues.entrySet()) {
            postData.append(pItem.getKey());
            postData.append("=");
            postData.append(java.net.URLEncoder.encode(pItem.getValue(), "UTF-8"));
            postData.append("&");
        }

        try {
            // Send the request
            java.net.URL url = new java.net.URL(
                    baseURL + funcName);
            java.net.URLConnection conn = url.openConnection();
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(120000);
            if (conn instanceof java.net.HttpURLConnection) {
                ((java.net.HttpURLConnection) conn).setRequestMethod("POST");
            }
            if (postData.length() > 0) {
                conn.setDoOutput(true);
                java.io.OutputStreamWriter writer = new java.io.OutputStreamWriter(
                        conn.getOutputStream());
                // write parameters
                writer.write(postData.toString());
                writer.flush();
                writer.close();
            }

            // Get the response
            String line = "";
            StringBuffer answer = new StringBuffer();
            java.io.BufferedReader reader = new java.io.BufferedReader(
                    new java.io.InputStreamReader(conn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                answer.append(line);
            }
            reader.close();
            // Output the response
            String msgID = answer.toString();
            if ((msgID.indexOf(':') > 0)
                    && (msgID.indexOf(':') + 11 > msgID.length())) {
                msgID = msgID.substring(msgID.indexOf(':') + 1);
            }

            return msgID;
        } catch (java.net.MalformedURLException ex) {
            ex.printStackTrace();
        } catch (java.io.IOException ex) {
            ex.printStackTrace();
        }
        // return VariantPool.get("ERRO");
        return "ERRO";
    }
}
