package com.fp.frontend.utility;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIInput;
import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.SystemEvent;
import javax.faces.event.SystemEventListener;

import org.primefaces.context.RequestContext;

//@ListenerFor(sourceClass = HtmlInputTextarea.class, systemEventClass = PostValidateEvent.class)
public class TextAreaValidationRequired implements SystemEventListener {

    private static ResourceBundle resource_bundle = ResourceBundle
            .getBundle("controlarmas_es");

    private static ResourceBundle resource_bundleValidacion = ResourceBundle
            .getBundle("validation_es");

    @Override
    public boolean isListenerForSource(Object arg0) {
        // TODO Auto-generated method stub

        if (arg0 instanceof HtmlInputTextarea) {
            UIInput source = (UIInput) arg0;
            if (source.isValid()) {
                HtmlInputTextarea auxTextArea = ((HtmlInputTextarea) arg0);
                if (auxTextArea.getAttributes().get("required").toString()
                        .equalsIgnoreCase("true")) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void processEvent(SystemEvent event) throws AbortProcessingException {

        // TODO Auto-generated method stub
        if (event.getSource() instanceof HtmlInputTextarea) {
            UIInput source = (UIInput) event.getSource();
            Object object = source.getAttributes().get("maxlength");
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            if (object != null
                    && object.toString() != ""
                    && Integer.parseInt(object.toString()) < source.getValue()
                    .toString().length()) {
                source.setValid(false);
                RequestContext.getCurrentInstance().addCallbackParam("validationFailed", true);
                String mensajeValidacion = getMessagesResources(resource_bundle,
                        "msg_tamanioMaximoExcedido",
                        new Object[]{source.getRequiredMessage() == null ? "" : source.getRequiredMessage(),
                            object.toString()});
                message.setSummary(mensajeValidacion);
                message.setDetail(mensajeValidacion);
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(
                        source.getClientId(), message);

                return;
            }
            if (source.getValue() != null
                    && source.getValue().toString().trim().equals("")) {

                source.setValid(false);
                if (FacesContext.getCurrentInstance().getPartialViewContext()
                        .isAjaxRequest()) {
                    RequestContext.getCurrentInstance().addCallbackParam("validationFailed", true);
                    String mensajeValidacion = null;
                    mensajeValidacion = source.getRequiredMessage();
                    if (mensajeValidacion == null || mensajeValidacion.equals("")) {
                        mensajeValidacion = getMessagesResources(resource_bundleValidacion,
                                "javax.faces.component.UIInput.REQUIRED",
                                new Object[]{source.getRequiredMessage(),
                                    object.toString()});
                        message.setSummary(mensajeValidacion);

                        String mensajeValidacionDetalle = getMessagesResources(resource_bundleValidacion,
                                "javax.faces.component.UIInput.REQUIRED_detail",
                                new Object[]{source.getRequiredMessage(),
                                    object.toString()});
                        message.setDetail(mensajeValidacionDetalle);
                    }

                    message.setSummary(mensajeValidacion);

                    message.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(
                            source.getClientId(), message);
                    return;

                }

            }

        }

    }

    private String getMessagesResources(ResourceBundle resourceBundle, String key, Object[] argumentos) {
        String resourceString = "";
        try {

            resourceString = resourceBundle.getString(key);

        } catch (MissingResourceException e) {
            return key;
        }
        MessageFormat format = new MessageFormat(resourceString);

        return format.format(argumentos);
    }

}
