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

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

import com.tibbo.aggregate.common.Cres;
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 class FormatDateFunction extends AbstractFunction
{
  public FormatDateFunction()
  {
    super("formatDate", Function.GROUP_DATE_TIME_PROCESSING, "Date date, String pattern [, String timezone]", "String", Cres.get().getString("fDescFormatDate"));
  }
  
  @Override
  public Object execute(Evaluator evaluator, EvaluationEnvironment environment, Object... parameters) throws EvaluationException
  {
    checkParameters(2, false, parameters);
    
    Date date = Util.convertToDate(parameters[0], true, false);
    String pattern = parameters[1].toString();
    
    if (date == null)
    {
      return "";
    }

    ZoneId zoneId = DateUtils.UTC_TIME_ZONE.toZoneId();
    
    if (parameters.length > 2)
    {
      String zone = parameters[2].toString();
      if (!Strings.isEmpty(zone))
      {
        zoneId = ZoneId.of(zone);
      }
    }

    // Convert Date to Instant, then to ZonedDateTime
    ZonedDateTime zonedDateTime = date.toInstant()
            .atZone(zoneId);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

    return zonedDateTime.format(formatter);
  }
}
