
package de.ivu.elect.jee.faces;

import java.io.Serializable;
import java.util.Optional;

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

import de.ivu.elect.jee.cdi.BeanManagerUtil;
import de.ivu.elect.jee.cron.Crontab;

public class CronExpressionValidator implements Validator, Serializable {

  private static final long serialVersionUID = 1L;

  @Override
  public void validate(FacesContext facesContext, UIComponent uiComponent, Object obj) throws ValidatorException {
    if (obj == null) {
      return;
    }

    String expression = obj.toString();

    try {
      Crontab cron = Crontab.forCrontab(expression);

      Optional<ScheduleExpression> scheduleExpression = cron.getScheduleExpression();

      if (!scheduleExpression.isPresent()) {
        return;
      }

      // ELECT-8731
      if (expression != null && expression.contains("/0")) {
        throw new ValidatorException(FacesMessageUtil.createErrorMessage(facesContext,
            "cron.expression.validation.failed", "cron.expression.validation.failed.detail", expression));
      }

      CronExpressionValidatorTimerBean bean = BeanManagerUtil.getBeanByClass(CronExpressionValidatorTimerBean.class);

      if (!bean.isExpressionValid(scheduleExpression.get())) {
        throw new ValidatorException(FacesMessageUtil.createErrorMessage(facesContext,
            "cron.expression.validation.failed", "cron.expression.validation.failed.detail", expression));
      }

    } catch (IllegalStateException ex) {
      throw new ValidatorException(FacesMessageUtil.createErrorMessage(facesContext,
          "cron.expression.validation.failed", "cron.expression.validation.failed.detail", expression));
    }
  }
}
