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

import com.chenyang.druid.sql.ast.SQLExpr;
import com.chenyang.druid.sql.ast.expr.SQLMethodInvokeExpr;
import com.chenyang.druid.sql.visitor.SQLEvalVisitor;
import com.chenyang.druid.sql.visitor.SQLEvalVisitorUtils;

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

   public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
      if (x.getArguments().size() != 2) {
         return SQLEvalVisitor.EVAL_ERROR;
      } else {
         SQLExpr param0 = (SQLExpr)x.getArguments().get(0);
         SQLExpr param1 = (SQLExpr)x.getArguments().get(1);
         param0.accept(visitor);
         param1.accept(visitor);
         Object param0Value = param0.getAttributes().get("eval.value");
         Object param1Value = param1.getAttributes().get("eval.value");
         if (param0Value != null && param1Value != null) {
            String strValue = param0Value.toString();
            int intValue = SQLEvalVisitorUtils.castToInteger(param1Value);
            if (intValue > strValue.length()) {
               return SQLEvalVisitor.EVAL_ERROR;
            } else {
               String result = strValue.substring(0, intValue);
               return result;
            }
         } else {
            return SQLEvalVisitor.EVAL_ERROR;
         }
      }
   }
}
