
package de.ivu.elect.jee.faces;

import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.splitByWholeSeparator;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;

import java.io.Serializable;
import java.net.URI;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

// ELECT-5536
@FacesValidator("urlStringValidator")
public class UrlStringValidator implements Validator, Serializable {

  private static final long serialVersionUID = 1L;

  public static final String SUMMARY_KEY = "url.string.validator";

  public static final String DETAIL_KEY = SUMMARY_KEY + "_detail";

  public UrlStringValidator() {
    super();
  }

  @Override
  public void validate(FacesContext facesContext, UIComponent uiComponent, Object value) throws ValidatorException {
    try {
      validate(value);
    } catch (Exception ex) {
      throw new ValidatorException(FacesMessageUtil.createErrorMessage(facesContext, SUMMARY_KEY, DETAIL_KEY, FacesComponentUtil.getLocalizedLabelOrId(uiComponent), value));
    }
  }

  protected void validate(Object value) throws Exception {
    if (value == null) {
      return;
    }

    String[] valueSplitted = splitByWholeSeparator(value.toString(), "?");

    if (valueSplitted.length > 0) {
      String baseUrlString = trimToEmpty(valueSplitted[0]);

      if (isNotBlank(baseUrlString)) {
        URI.create(baseUrlString).toURL();
      }
    }
  }
}
