package br.com.elotech.dao.impl;

import br.com.elotech.model.AtivacaoParams;
import br.com.elotech.model.Registro;
import br.com.elotech.util.Crypto;
import br.com.elotech.util.CustomException;
import org.apache.commons.lang3.StringUtils;
import us.monoid.web.JSONResource;
import us.monoid.web.Resty;

import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;

public abstract class Bluemix {

    private static final String HOST = "license.elotech.com.br";
    private static final String REST = "/rest/licenses/";
    private static final String SCHEME = "http";
    private static final String INTERNAL_HOST_NAME = "192.168.1.250";
    private static final Integer INTERNAL_PORT = 3128;
    private static Map<String, String> env = System.getenv();
    private static DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    public static synchronized Registro verificar(AtivacaoParams params) throws Exception {
        Registro registro = null;
        try {
            String path = REST.concat(params.getCodigo()).concat("/").concat(params.getChave());
            URI uri = new URI(SCHEME, HOST, path, null);
            String pwd = env.get("PWD");

            if(StringUtils.isNotBlank(pwd) && pwd.toLowerCase().contains("elovirtual")){
                Resty.Proxy.proxy(INTERNAL_HOST_NAME, INTERNAL_PORT);
            }

            JSONResource res = new Resty().json(uri.toASCIIString());
            registro = new Registro();
            registro.setCodigo(res.get("cliente").toString());
            registro.setNome(res.get("name").toString());
            registro.setSistemaCodigo(res.get("code").toString().substring(0,3));
            registro.setModulo(res.get("module").toString());
            registro.setSenha(res.get("password").toString());
            registro.setValidade(formatter.parse(res.get("date").toString()));

            String hash = Crypto.geraHash(registro);
            registro.setHash(hash);
        } catch (Exception e) {
            e.printStackTrace();
            //bloqueia o sistema
            new CustomException(e, params);
        }
        return registro;
    }
}
