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.util.HexBin;
import java.io.UnsupportedEncodingException;

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

   public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
      if (x.getArguments().size() != 1) {
         return SQLEvalVisitor.EVAL_ERROR;
      } else {
         SQLExpr param0 = (SQLExpr)x.getArguments().get(0);
         if (param0 instanceof SQLMethodInvokeExpr) {
            SQLMethodInvokeExpr paramMethodExpr = (SQLMethodInvokeExpr)param0;
            if (paramMethodExpr.getMethodName().equalsIgnoreCase("hex")) {
               SQLExpr subParamExpr = (SQLExpr)paramMethodExpr.getArguments().get(0);
               subParamExpr.accept(visitor);
               Object param0Value = subParamExpr.getAttributes().get("eval.value");
               if (param0Value == null) {
                  x.putAttribute("eval.expr", subParamExpr);
                  return SQLEvalVisitor.EVAL_ERROR;
               }

               return param0Value;
            }
         }

         param0.accept(visitor);
         Object param0Value = param0.getAttributes().get("eval.value");
         if (param0Value == null) {
            return SQLEvalVisitor.EVAL_ERROR;
         } else if (param0Value instanceof String) {
            byte[] bytes = HexBin.decode((String)param0Value);
            if (bytes == null) {
               return SQLEvalVisitor.EVAL_VALUE_NULL;
            } else {
               try {
                  String result = new String(bytes, "UTF-8");
                  return result;
               } catch (UnsupportedEncodingException e) {
                  throw new IllegalStateException(e.getMessage(), e);
               }
            }
         } else {
            return SQLEvalVisitor.EVAL_ERROR;
         }
      }
   }
}
