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

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

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

   public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
      List<SQLExpr> arguments = x.getArguments();
      if (arguments.size() != 2) {
         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");
         if (v0 instanceof Date && v1 instanceof String) {
            Date date = (Date)v0;
            String format = ((SQLCharExpr)arguments.get(1)).getText();
            if (format.equals("yyyymmdd")) {
               SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
               return dateFormat.format(date);
            }
         }

         return null;
      }
   }
}
