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 com.alibaba.druid.sql.visitor.SQLEvalVisitorUtils;

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

   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);
            int start = strValue.length() - intValue;
            if (start < 0) {
               start = 0;
            }

            String result = strValue.substring(start, strValue.length());
            return result;
         } else {
            return SQLEvalVisitor.EVAL_ERROR;
         }
      }
   }
}
