package br.com.elotech.base;

import br.com.elotech.base.crypto.Crypto;
import br.com.elotech.base.interfaces.LicensaInterface;
import br.com.elotech.base.model.RegistroModel;
import br.com.elotech.base.model.dao.ConexaoDao;
import us.monoid.web.JSONResource;
import us.monoid.web.Resty;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URI;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * Classe responsável pela ativação do sistema
 */
public class AtivacaoSistema {

    final static String HOST = "ativador.elotech.com.br";
    //final static String HOST = "http://elotechlicense.mybluemix.net";
    final static String PATH = "/ativacao/";
    //final static String PATH = "/rest/licenses/";

    /**
     *Faz a consulta no servidor para ativar o sistema ou não
     * @param licensa implementação de ações ao expirar e código do sistema
     * @return entidade com as informações de retorno da comunicação com servidor
     */
    public static synchronized RegistroModel verificar(LicensaInterface licensa){
        System.out.println("verificar");
        RegistroModel registro = new RegistroModel();

        try {
            URI myUri = new URI(
                    "http",
                    HOST,
                    PATH+licensa.getCodigoSistema()+"/"+licensa.getNomeCliente(),
                    null);
            System.out.println(PATH+licensa.getCodigoSistema()+"/"+licensa.getNomeCliente());
            Map<String, String> env = System.getenv();

            String PWD = env.get("PWD");
            URLConnection con = null;
            boolean pro = false;
            Proxy proxy=null;
            if(PWD!=null)
                if(PWD.toLowerCase().contains("elovirtual")) {
                    Resty.Proxy.proxy("192.168.1.250",3128);
                }
            JSONResource json;
            ResultSet rs = ConexaoDao.getConnection().prepareStatement("show LC_COLLATE").executeQuery();
            rs.next();
            
            if(rs.getString(1).contains("UTF-8")){
                json = new Resty().json(myUri.toASCIIString());
                System.out.println("1myUri.toASCIIString() = "+myUri.toASCIIString());
//                System.out.println("1myUri.toASCIIString() = "+myUri.toString());
//                json = new Resty().json(myUri.toString());
            }else{
                String retValue = new String(licensa.getNomeCliente().getBytes(),
                    Charset.forName("Windows-1252"));
                myUri = new URI(
                    "http",
                    HOST,
                    PATH+licensa.getCodigoSistema()+"/"+retValue,
                    null);
                json = new Resty().json(myUri.toASCIIString());    
            }
            registro.setNome(json.get("cliente").toString());
            registro.setCodigo(json.get("code").toString());
            registro.setModulo(json.get("module").toString());
            registro.setNome(json.get("name").toString());
            registro.setSenha(json.get("password").toString());
            registro.setValidade(LocalDate.parse(json.get("date").toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd")));

            if(registro.getValidade().isBefore(LocalDate.now()))
                licensa.expirouSistema(registro);

            return registro;
        } catch (IOException e) {
            e.printStackTrace();
            licensa.ocorreuErroNaComunicacao(e,null);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            licensa.ocorreuErroNaComunicacao(null,e);
            return null;
        }

    }

    /**
     * Verifica se os dados não forão alterados diretamente no banco de dados
     * @param registro preencha corretamente para comparar o hash
     * @param hashDatabase hash do banco de dados referente aos dados preenchidos
     * @param licensa caso o registro seja inválido executa o expirouSistema
     * @return executa a interface de bloqueio caso esteja alterado e retorna false, se true é válido
     */
    public static boolean verificaIntegridadeLicensa(RegistroModel registro, String hashDatabase,LicensaInterface licensa){

        if(!hashDatabase.equals(registro.getHash())) {
            licensa.expirouSistema(registro);
            return false;
        }

        return true;
    }


}
