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;

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

   public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
      if (x.getArguments().size() != 4) {
         return SQLEvalVisitor.EVAL_ERROR;
      } else {
         SQLExpr param0 = (SQLExpr)x.getArguments().get(0);
         SQLExpr param1 = (SQLExpr)x.getArguments().get(1);
         SQLExpr param2 = (SQLExpr)x.getArguments().get(2);
         SQLExpr param3 = (SQLExpr)x.getArguments().get(3);
         param0.accept(visitor);
         param1.accept(visitor);
         param2.accept(visitor);
         param3.accept(visitor);
         Object param0Value = param0.getAttributes().get("eval.value");
         Object param1Value = param1.getAttributes().get("eval.value");
         Object param2Value = param2.getAttributes().get("eval.value");
         Object param3Value = param3.getAttributes().get("eval.value");
         if (!(param0Value instanceof String)) {
            return SQLEvalVisitor.EVAL_ERROR;
         } else if (!(param1Value instanceof Number)) {
            return SQLEvalVisitor.EVAL_ERROR;
         } else if (!(param2Value instanceof Number)) {
            return SQLEvalVisitor.EVAL_ERROR;
         } else if (!(param3Value instanceof String)) {
            return SQLEvalVisitor.EVAL_ERROR;
         } else {
            String str = (String)param0Value;
            int pos = ((Number)param1Value).intValue();
            int len = ((Number)param2Value).intValue();
            String newstr = (String)param3Value;
            if (pos <= 0) {
               return str;
            } else if (pos == 1) {
               return len > str.length() ? newstr : newstr + str.substring(len);
            } else {
               String first = str.substring(0, pos - 1);
               return pos + len - 1 > str.length() ? first + newstr : first + newstr + str.substring(pos + len - 1);
            }
         }
      }
   }
}
