package com.tibbo.aggregate.common.expression.function.date;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

import com.tibbo.aggregate.common.expression.EvaluationEnvironment;
import com.tibbo.aggregate.common.expression.EvaluationException;
import com.tibbo.aggregate.common.expression.Evaluator;
import com.tibbo.aggregate.common.expression.Function;
import com.tibbo.aggregate.common.expression.function.AbstractFunction;
import com.tibbo.aggregate.common.util.DateUtils;
import com.tibbo.aggregate.common.util.Util;
import org.apache.logging.log4j.util.Strings;

public abstract class DateFunction extends AbstractFunction
{
  public DateFunction(String name, String returnValue, String description)
  {
    super(name, Function.GROUP_DATE_TIME_PROCESSING, "Date date [, String timezone]", returnValue, description);
  }
  
  @Override
  public Object execute(Evaluator evaluator, EvaluationEnvironment environment, Object... parameters) throws EvaluationException
  {
    checkParameters(1, false, parameters);
    
    ZoneId zoneId = DateUtils.UTC_TIME_ZONE.toZoneId();
    
    if (parameters.length > 1)
    {
      String zone = parameters[1].toString();
      if (!Strings.isEmpty(zone))
      {
        zoneId = ZoneId.of(zone);
      }
    }

    Date date = Util.convertToDate(parameters[0], true, false);
    ZonedDateTime zonedDateTime = date.toInstant()
            .atZone(zoneId);
    return execute(zonedDateTime, parameters);
  }
  
  public abstract Object execute(ZonedDateTime dateTime, Object... parameters) throws EvaluationException;
}
