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.ast.expr.SQLValuableExpr;
import com.chenyang.druid.sql.visitor.SQLEvalVisitor;
import java.util.List;

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

   public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
      List<SQLExpr> arguments = x.getArguments();
      if (arguments.size() != 2) {
         return SQLEvalVisitor.EVAL_ERROR;
      } else {
         SQLExpr condition = (SQLExpr)arguments.get(0);
         condition.accept(visitor);
         Object itemValue = condition.getAttributes().get("eval.value");
         if (itemValue == null) {
            SQLExpr valueExpr = (SQLExpr)arguments.get(1);
            valueExpr.accept(visitor);
            return valueExpr.getAttributes().get("eval.value");
         } else {
            return itemValue;
         }
      }
   }

   public Object eval(SQLMethodInvokeExpr x) {
      List<SQLExpr> arguments = x.getArguments();
      if (arguments.size() != 2) {
         return SQLEvalVisitor.EVAL_ERROR;
      } else {
         SQLExpr condition = (SQLExpr)arguments.get(0);
         SQLExpr valueExpr = (SQLExpr)arguments.get(1);
         if (condition instanceof SQLValuableExpr && valueExpr instanceof SQLValuableExpr) {
            Object itemValue = ((SQLValuableExpr)condition).getValue();
            return itemValue != null && itemValue != SQLEvalVisitor.EVAL_VALUE_NULL ? itemValue : ((SQLValuableExpr)valueExpr).getValue();
         } else {
            return SQLEvalVisitor.EVAL_ERROR;
         }
      }
   }
}
