package com.alibaba.druid.sql.visitor.functions;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
import com.alibaba.druid.sql.visitor.SQLEvalVisitor;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateAdd implements Function {
   public static final DateAdd instance = new DateAdd();

   public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
      List<SQLExpr> arguments = x.getArguments();
      if (arguments.size() != 3) {
         return SQLEvalVisitor.EVAL_ERROR;
      } else {
         for(SQLExpr arg : arguments) {
            arg.accept(visitor);
         }

         Object v0 = ((SQLExpr)arguments.get(0)).getAttributes().get("eval.value");
         Object v1 = ((SQLExpr)arguments.get(1)).getAttributes().get("eval.value");
         Object v2 = ((SQLExpr)arguments.get(2)).getAttributes().get("eval.value");
         if (v0 instanceof Date && v1 instanceof Integer && v2 instanceof String) {
            Date date = (Date)v0;
            int delta = (Integer)v1;
            if ("day".equalsIgnoreCase((String)v2)) {
               Calendar calendar = Calendar.getInstance();
               calendar.setTime(date);
               calendar.add(5, delta);
               return calendar.getTime();
            }
         }

         SQLExpr arg = (SQLExpr)arguments.get(0);
         arg.accept(visitor);
         Object itemValue = arg.getAttributes().get("eval.value");
         return itemValue == null ? null : null;
      }
   }
}
