package br.com.centralit.citcorpore.ajaxForms;

import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.centralit.authentication.Auth;
import br.com.centralit.citajax.html.AjaxFormAction;
import br.com.centralit.citajax.html.DocumentHTML;
import br.com.centralit.citajax.html.HTMLElement;
import br.com.centralit.citcorpore.bean.ValidarChaveSegurancaDTO;
import br.com.centralit.citcorpore.versao.Versao;
import br.com.centralit.dto.L;
import br.com.centralit.util.AuthEncryption;
import br.com.citframework.util.UtilI18N;

public class ValidarChaveSeguranca extends AjaxFormAction {

	private AuthEncryption authEncryption;

	@Override
	public void load(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, String> props = getAuthEncryption().rp();

		if (props != null && props.get("l") != null && !props.get("l").isEmpty()) {
			HTMLElement chave = document.getElementById("chave");
			chave.setValue(props.get("l"));
		}

		String k = null;
		if (props != null && props.get("k") != null && !props.get("k").isEmpty()) {
			k = props.get("k");
		} else {
			k = UUID.randomUUID().toString();
		}

		HTMLElement genKey = document.getElementById("genKey");
		genKey.setValue(k);
	}

	/**
	 * Força a validação da licença do cliente.
	 * 
	 * @param document
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void validarChave(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		final ValidarChaveSegurancaDTO validarChaveSegurancaDTO = (ValidarChaveSegurancaDTO) document.getBean();

		if (validarChaveSegurancaDTO.getChave() != null && !validarChaveSegurancaDTO.getChave().isEmpty()) {
			L l = new L();
			l.setA(validarChaveSegurancaDTO.getChave());
			l.setI(Versao.getVersao());
			l.setJ(Versao.getTipoAplicacao());
			l.setK(validarChaveSegurancaDTO.getGenKey());

			L lCheck = Auth.cl(l);

			if (lCheck != null) {
				if (lCheck.isC()) {
					Auth.cp(l, true);

					document.alert(UtilI18N.internacionaliza(request, "validarChaveSeguranca.validacaoRealizada"));
				} else {
					document.alert(UtilI18N.internacionaliza(request, "validarChaveSeguranca.validacaoRealizadaInvalida"));
				}

				return;
			} else {
				document.alert(UtilI18N.internacionaliza(request, "validarChaveSeguranca.validacaoNaoRealizada") + ".");
			}
		} else {
			document.alert(UtilI18N.internacionaliza(request, "validarChaveSeguranca.validacaoNaoRealizada"));
		}
	}

	public AuthEncryption getAuthEncryption() {
		if (authEncryption == null) {
			authEncryption = new AuthEncryption();
		}

		return authEncryption;
	}

	@Override
	public Class<ValidarChaveSegurancaDTO> getBeanClass() {
		return ValidarChaveSegurancaDTO.class;
	}

}
