package util.sqlparse.visitor.hivetdh;

import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlArithmetic;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;

import java.util.HashMap;
import java.util.Map;

public class ExlActor {
   public static Object replace(String expression, Object value) {
      expression = expression.replace("${value}", "_value");
      Object code = convertToCode(expression, value);
      return code;
   }

   public static Object convertToCode(String jexlExp, Object value) {
      Map<String, Object> map = new HashMap(16);
      map.put("_value", value);
      map.put(null, new ExlFunctionProvider());
      JexlEngine jexl = new JexlEngine(new UberspectImpl(), (JexlArithmetic)null, map, null);
      jexl.setDebug(false);
      Expression e = jexl.createExpression(jexlExp);
      JexlContext jc = new MapContext();

      for(String key : map.keySet()) {
         jc.set(key, map.get(key));
      }

      return e.evaluate(jc);
   }

   public static void main(String... args) throws Exception {
      try {
         String[] expressions = new String[]{"unix_timestamp(now())", "from_unixtime(unix_timestamp(now()))", "date(from_unixtime(unix_timestamp('1970-01-01') + floor(rand() * ( unix_timestamp(NOW()) - unix_timestamp('1970-01-01') + 1 ))))", "date(from_unixtime(unix_timestamp('1970-01-01 11:30:01') + floor(rand() * ( unix_timestamp(current_timestamp()) - unix_timestamp('1970-01-01 11:30:01') + 1 ))))", "'abcd' + 'aaaa'", "substr('张三分',1,1) + '***'", "substr('abcd',-9,2)", "substr('abcd',1,2)", "substr('abcde',1,3)", "substr('abcde',1,4)", "substr('abcde',1,5)", "concat('abcde','1','5')", "concat('abcde','1','5','5')", "substr('abcde',4,1)", "substr(substring('123',0,2),0,2)", "CEILING(RAND()*900+100)", "now()", "floor(20 + (random()*71))", "(substr('192.168.2.111',1,length('192.168.2.111')-3)+'***')", "floor(random()*900+100)", "left('50512345678@qq.com',3)+ '********' + substr('50512345678@qq.com',position('50512345678@qq.com','@'))", "concat(substr('ddddddddddd',0,3), '********')", "concat(substr('ddddddddddd',0,3), '********')", "concat(substr( 'ddddd@dddddd', 1, 3 ),'********',substr('ddddd@dddddd',INSTR( 'ddddd@dddddd', '@' )))", "concat(substr('ddddddddddd',0,length('ddddddddddd')-3), '***')", "concat(substr('ddddddddddd',0,5), '*******')", "CEILING(RAND()*900+100)", "mask('test', '*', 2, 3)", "mask('test', '*', 1, 8)", "mask('test', '$', 1, 8)"};

         for(String expression : expressions) {
            Object code = replace(expression, null);
            System.out.println(code);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

   }
}
