package util.sqlparse.visitor.postgresql.visitor;

import com.chenyang.druid.sql.ast.SQLExpr;
import com.chenyang.druid.sql.ast.SQLLimit;
import com.chenyang.druid.sql.ast.SQLName;
import com.chenyang.druid.sql.ast.SQLObject;
import com.chenyang.druid.sql.ast.SQLStatement;
import com.chenyang.druid.sql.ast.expr.SQLBetweenExpr;
import com.chenyang.druid.sql.ast.expr.SQLBigIntExpr;
import com.chenyang.druid.sql.ast.expr.SQLBinaryExpr;
import com.chenyang.druid.sql.ast.expr.SQLBinaryOpExpr;
import com.chenyang.druid.sql.ast.expr.SQLBooleanExpr;
import com.chenyang.druid.sql.ast.expr.SQLCaseExpr;
import com.chenyang.druid.sql.ast.expr.SQLCharExpr;
import com.chenyang.druid.sql.ast.expr.SQLDateExpr;
import com.chenyang.druid.sql.ast.expr.SQLDateTimeExpr;
import com.chenyang.druid.sql.ast.expr.SQLDecimalExpr;
import com.chenyang.druid.sql.ast.expr.SQLDoubleExpr;
import com.chenyang.druid.sql.ast.expr.SQLExistsExpr;
import com.chenyang.druid.sql.ast.expr.SQLFloatExpr;
import com.chenyang.druid.sql.ast.expr.SQLHexExpr;
import com.chenyang.druid.sql.ast.expr.SQLInListExpr;
import com.chenyang.druid.sql.ast.expr.SQLInSubQueryExpr;
import com.chenyang.druid.sql.ast.expr.SQLIntegerExpr;
import com.chenyang.druid.sql.ast.expr.SQLJSONExpr;
import com.chenyang.druid.sql.ast.expr.SQLListExpr;
import com.chenyang.druid.sql.ast.expr.SQLMethodInvokeExpr;
import com.chenyang.druid.sql.ast.expr.SQLNCharExpr;
import com.chenyang.druid.sql.ast.expr.SQLNullExpr;
import com.chenyang.druid.sql.ast.expr.SQLNumberExpr;
import com.chenyang.druid.sql.ast.expr.SQLRealExpr;
import com.chenyang.druid.sql.ast.expr.SQLSmallIntExpr;
import com.chenyang.druid.sql.ast.expr.SQLTimeExpr;
import com.chenyang.druid.sql.ast.expr.SQLTimestampExpr;
import com.chenyang.druid.sql.ast.expr.SQLTinyIntExpr;
import com.chenyang.druid.sql.ast.expr.SQLUnaryExpr;
import com.chenyang.druid.sql.ast.expr.SQLValuableExpr;
import com.chenyang.druid.sql.ast.expr.SQLVariantRefExpr;
import com.chenyang.druid.sql.ast.statement.SQLAssignItem;
import com.chenyang.druid.sql.ast.statement.SQLInsertStatement;
import com.chenyang.druid.sql.ast.statement.SQLMergeStatement;
import com.chenyang.druid.sql.ast.statement.SQLSelect;
import com.chenyang.druid.sql.ast.statement.SQLSelectItem;
import com.chenyang.druid.sql.ast.statement.SQLUpdateSetItem;
import com.chenyang.druid.sql.ast.statement.SQLValuesTableSource;
import com.chenyang.druid.sql.dialect.postgresql.ast.stmt.PGInsertStatement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import util.sqlparse.visitor.common.memo.FieldMemo;
import util.sqlparse.visitor.common.memo.ValueMemo;
import util.sqlparse.visitor.common.scope.Scope;
import util.sqlparse.visitor.common.utils.Alias;

public class FieldVisitor extends ParseVisitor {
   private static final String QUESTION_MARK = "?";
   private static final String FUNC_IFNULL = "ifnull";
   private static final String FUNC_NVL = "nvl";
   private final Alias alias = new Alias();

   public FieldVisitor(Scope scope) {
      super(scope);
   }

   public boolean visit(SQLVariantRefExpr x) {
      this.setValue(x);
      return true;
   }

   private void setValue(SQLExpr valueExpr) {
      SQLObject parent = valueExpr.getParent();
      if (parent != null) {
         if (parent instanceof SQLUnaryExpr) {
            this.setUnary(valueExpr, parent);
         } else if (parent instanceof SQLBinaryOpExpr) {
            this.setBinary(valueExpr, parent);
         } else if (parent instanceof SQLCaseExpr.Item) {
            this.setCase(valueExpr, parent);
         } else if (parent instanceof SQLMethodInvokeExpr) {
            this.setMethod(valueExpr, parent);
         } else if (parent instanceof SQLExistsExpr) {
            this.setExists(valueExpr, parent);
         } else if (parent instanceof SQLInListExpr) {
            this.setInList(valueExpr, parent);
         } else if (parent instanceof SQLInsertStatement.ValuesClause) {
            this.setInsertOrReplaceItem(valueExpr, parent);
         } else if (parent instanceof SQLMergeStatement.MergeInsertClause) {
            this.setMergeInsertItem(valueExpr, parent);
         } else if (parent instanceof SQLMergeStatement.MergeUpdateClause) {
            this.setMergeUpdateItem(valueExpr, parent);
         } else if (parent instanceof SQLUpdateSetItem) {
            this.setUpdateItem(valueExpr, parent);
         } else if (parent instanceof SQLInSubQueryExpr) {
            this.setInSubQuery(valueExpr, parent);
         } else if (parent instanceof SQLLimit) {
            this.setLimit(valueExpr, parent);
         } else if (parent instanceof SQLBetweenExpr) {
            this.setBetween(valueExpr, parent);
         } else if (parent instanceof SQLSelectItem) {
            this.setSelectItem(valueExpr, parent);
         } else if (parent instanceof SQLListExpr) {
            this.setListExpr(valueExpr, parent);
         } else {
            this.setOther(valueExpr, parent);
         }
      }

   }

   private void setListExpr(SQLExpr valueExpr, SQLObject parent) {
      SQLObject pa = parent.getParent();
      SQLListExpr columns;
      int i;
      List valueItems;
      int index;
      ValueMemo value;
      if (pa instanceof SQLUpdateSetItem) {
         SQLUpdateSetItem setItem = (SQLUpdateSetItem)pa;
         columns = (SQLListExpr)setItem.getColumn();
         i = 0;
         SQLListExpr item = (SQLListExpr)parent;
         valueItems = item.getItems();

         for(index = 0; index < valueItems.size(); ++index) {
            if (valueItems.get(index) == valueExpr) {
               i = index;
               break;
            }
         }

         value = this.getValueMemo((SQLExpr)columns.getItems().get(i), valueExpr);
         value.setRef(valueExpr);
         value.setExpr(parent);
         value.setValue(this.getValue(valueExpr));
         value.setPreDefined(value.toString().equals("?"));
         value.setOperator("SET");
         this.scope.getValues().add(value);
      } else if (pa instanceof SQLAssignItem) {
         SQLAssignItem assignItem = (SQLAssignItem)pa;
         columns = (SQLListExpr)assignItem.getTarget();
         SQLListExpr value2 = (SQLListExpr)assignItem.getValue();
         List<SQLExpr> targetItems = columns.getItems();
         valueItems = value2.getItems();
         index = 0;

         for(int i1 = 0; i1 < valueItems.size(); ++i1) {
            if (valueItems.get(i1) == valueExpr) {
               index = i1;
               break;
            }
         }

         ValueMemo val = this.getValueMemo((SQLExpr)targetItems.get(index), valueExpr);
         val.setRef(valueExpr);
         val.setExpr(parent);
         val.setValue(this.getValue(valueExpr));
         val.setPreDefined(value2.toString().equals("?"));
         val.setOperator("SET");
         this.scope.getValues().add(val);
      } else if (pa instanceof SQLValuesTableSource) {
         SQLValuesTableSource tableSource = (SQLValuesTableSource)pa;
         index = 0;

         for(i = 0; i < ((SQLListExpr)parent).getItems().size(); ++i) {
            if (((SQLListExpr)parent).getItems().get(i) == valueExpr) {
               index = i;
               break;
            }
         }

         List<SQLName> columns1 = tableSource.getColumns();
         if (columns1 != null && columns1.size() > 0) {
            int size = columns1.size();
            index %= size;
            SQLExpr columnExpr = (SQLExpr)columns1.get(index);
            value = this.getValueMemo(columnExpr, valueExpr);
            value.setRef(valueExpr);
            value.setExpr(parent);
            value.setValue(this.getValue(valueExpr));
            value.setPreDefined(value.toString().equals("?"));
            value.setOperator("SET");
            this.scope.getValues().add(value);
         }
      } else {
         this.setOther(valueExpr, parent);
      }

   }

   private void setSelectItem(SQLExpr valueExpr, SQLObject parent) {
      ValueMemo value = this.getValueMemo(valueExpr, valueExpr);
      value.setRef(valueExpr);
      value.setExpr(parent);
      value.setValue(this.getValue(valueExpr));
      value.setOperator("SELECT_ITEM");
      this.scope.getValues().add(value);
   }

   private void setUnary(SQLExpr valueExpr, SQLObject parent) {
      ValueMemo value = this.getValueMemo((SQLExpr)null, valueExpr);
      value.ref = valueExpr;
      value.expr = parent;
      value.value = this.getValue(valueExpr);
      if (value.operator == null) {
         SQLUnaryExpr unary = (SQLUnaryExpr)parent;
         value.operator = unary.getOperator().name;
      } else {
         value.operator = value.operator.toUpperCase();
      }

      value.isPreDefined = value.toString().equals("?");
      this.scope.getValues().add(value);
   }

   private void setBinary(SQLExpr valueExpr, SQLObject parent) {
      SQLBinaryOpExpr opExpr = (SQLBinaryOpExpr)parent;
      SQLExpr leftExpr = opExpr.getLeft();
      SQLExpr rightExpr = opExpr.getRight();
      SQLExpr varExpr;
      if (leftExpr.equals(valueExpr)) {
         varExpr = rightExpr;
      } else {
         varExpr = leftExpr;
      }

      ValueMemo value = this.getValueMemo(varExpr, valueExpr);
      value.ref = valueExpr;
      value.expr = parent;
      value.value = this.getValue(valueExpr);
      value.operator = opExpr.getOperator().getName().toUpperCase();
      value.isPreDefined = value.toString().equals("?");
      this.scope.getValues().add(value);
   }

   private void setCase(SQLExpr valueExpr, SQLObject parent) {
      SQLCaseExpr.Item itemExpr = (SQLCaseExpr.Item)parent;
      SQLCaseExpr caseExpr = (SQLCaseExpr)itemExpr.getParent();
      ValueMemo value = this.getValueMemo(caseExpr.getValueExpr(), valueExpr);
      value.ref = valueExpr;
      value.expr = itemExpr;
      value.value = this.getValue(valueExpr);
      value.operator = "CASE";
      value.isPreDefined = value.toString().equals("?");
      this.scope.getValues().add(value);
   }

   private void setMethod(SQLExpr valueExpr, SQLObject parent) {
      if (!valueExpr.toString().equals("'%'")) {
         SQLMethodInvokeExpr methodExpr = (SQLMethodInvokeExpr)parent;
         String method = methodExpr.getMethodName();
         boolean done = false;
         if (method.equalsIgnoreCase("ifnull") || method.equalsIgnoreCase("nvl")) {
            SQLExpr expr = (SQLExpr)methodExpr.getArguments().get(0);
            ValueMemo value = this.getValueMemo(expr, valueExpr, true);
            if (value != null && value.field != null) {
               value.ref = valueExpr;
               value.expr = parent;
               value.value = this.getValue(valueExpr);
               value.operator = method.toUpperCase();
               value.isPreDefined = value.toString().equals("?");
               this.scope.getValues().add(value);
               done = true;
            }
         }

         if (!done) {
            List<String> operators = new ArrayList();
            SQLExpr expr = this.getSqlExpr(valueExpr.getParent(), valueExpr, operators);
            ValueMemo value = this.getValueMemo(expr, valueExpr);
            value.ref = valueExpr;
            value.expr = parent;
            value.value = this.getValue(valueExpr);
            if (value.operator == null) {
               if (operators.size() > 0) {
                  value.operator = (String)operators.get(0);
               } else {
                  value.operator = "OTHER";
               }
            }

            value.isPreDefined = value.toString().equals("?");
            this.scope.getValues().add(value);
         }

      }
   }

   private SQLExpr getSqlExpr(SQLObject x, SQLObject y, List<String> operators) {
      if (!(x instanceof SQLName) && !(x instanceof SQLValuableExpr)) {
         if (x instanceof SQLSelectItem) {
            return ((SQLSelectItem)x).getExpr();
         } else if (x == null) {
            return null;
         } else if (x instanceof SQLStatement) {
            return null;
         } else if (x instanceof SQLSelect) {
            return null;
         } else {
            if (x instanceof SQLBinaryOpExpr) {
               SQLBinaryOpExpr bin = (SQLBinaryOpExpr)x;
               if (bin.getOperator() != null) {
                  SQLExpr cmp;
                  switch (bin.getOperator()) {
                     case Like:
                     case Like2:
                     case Like4:
                     case Likec:
                        cmp = bin.getLeft().equals(y) ? bin.getRight() : bin.getLeft();
                        operators.add("LIKE");
                        return cmp;
                     case Equality:
                     case GreaterThan:
                     case GreaterThanOrEqual:
                     case LessThan:
                     case LessThanOrEqual:
                        cmp = bin.getLeft().equals(y) ? bin.getRight() : bin.getLeft();
                        operators.add(bin.getOperator().getName().toUpperCase());
                        return cmp;
                     case BooleanAnd:
                     case BooleanOr:
                        if (y instanceof SQLExpr) {
                           operators.add("OTHER");
                           return (SQLExpr)y;
                        }
                  }
               }
            }

            if (x instanceof SQLInListExpr) {
               operators.add("IN");
               SQLInListExpr inList = (SQLInListExpr)x;
               int idx = inList.getTargetList().indexOf(x);
               return idx != -1 ? (SQLExpr)inList.getTargetList().get(idx) : inList.getExpr();
            } else {
               SQLObject parent = x.getParent();
               return !(parent instanceof SQLExpr) ? null : this.getSqlExpr(parent, x, operators);
            }
         }
      } else {
         return (SQLExpr)x;
      }
   }

   private void setExists(SQLExpr valueExpr, SQLObject parent) {
      ValueMemo value = this.getValueMemo((SQLExpr)null, valueExpr);
      value.ref = valueExpr;
      value.expr = parent;
      value.value = this.getValue(valueExpr);
      value.isPreDefined = value.toString().equals("?");
      this.scope.getValues().add(value);
   }

   private void setInList(SQLExpr valueExpr, SQLObject parent) {
      SQLInListExpr inListExpr = (SQLInListExpr)parent;
      ValueMemo value = this.getValueMemo(inListExpr.getExpr(), valueExpr);
      value.ref = valueExpr;
      value.expr = inListExpr;
      value.value = this.getValue(valueExpr);
      value.isPreDefined = value.toString().equals("?");
      value.operator = "IN";
      this.scope.getValues().add(value);
   }

   private void setInsertOrReplaceItem(SQLExpr valueExpr, SQLObject parent) {
      SQLInsertStatement.ValuesClause clause = (SQLInsertStatement.ValuesClause)parent;
      int index = 0;

      for(int i = 0; i < clause.getValues().size(); ++i) {
         if (clause.getValues().get(i) == valueExpr) {
            index = i;
            break;
         }
      }

      List<FieldMemo> fields = new ArrayList();
      List<SQLExpr> columns = null;
      if (clause.getParent() instanceof PGInsertStatement) {
         PGInsertStatement insert = (PGInsertStatement)clause.getParent();
         columns = insert.getColumns();
         if (insert.getQuery() != null) {
            SQLSelect query = insert.getQuery();
            Scope selectScope = this.scope.getScope(query);
            Iterator i$ = selectScope.getFieldMap().orderValues().iterator();

            while(i$.hasNext()) {
               FieldMemo orderValue = (FieldMemo)i$.next();
               if (orderValue.isSelectItem) {
                  fields.add(orderValue);
               }
            }
         }
      }

      int size;
      ValueMemo value;
      if (columns != null && columns.size() > 0) {
         size = columns.size();
         index %= size;
         SQLExpr columnExpr = (SQLExpr)columns.get(index);
         value = this.getValueMemo(columnExpr, valueExpr);
         value.ref = valueExpr;
         value.expr = parent;
         value.value = this.getValue(valueExpr);
         value.isPreDefined = value.toString().equals("?");
         value.operator = "SET";
         this.scope.getValues().add(value);
      } else if (fields != null && fields.size() > 0) {
         size = fields.size();
         index %= size;
         FieldMemo field = (FieldMemo)fields.get(index);
         value = new ValueMemo();
         value.field = field;
         value.ref = valueExpr;
         value.expr = parent;
         value.value = this.getValue(valueExpr);
         value.isPreDefined = value.toString().equals("?");
         value.operator = "SET";
         this.scope.getValues().add(value);
      }

   }

   private void setMergeInsertItem(SQLExpr valueExpr, SQLObject parent) {
      SQLMergeStatement.MergeInsertClause clause = (SQLMergeStatement.MergeInsertClause)parent;
      int index = 0;

      for(int i = 0; i < clause.getValues().size(); ++i) {
         if (clause.getValues().get(i) == valueExpr) {
            index = i;
            break;
         }
      }

      List<SQLExpr> columns = clause.getColumns();
      if (columns != null && columns.size() > 0) {
         int size = columns.size();
         index %= size;
         SQLExpr columnExpr = (SQLExpr)columns.get(index);
         ValueMemo value = this.getValueMemo(columnExpr, valueExpr);
         value.ref = valueExpr;
         value.expr = parent;
         value.value = this.getValue(valueExpr);
         value.isPreDefined = value.toString().equals("?");
         value.operator = "SET";
         this.scope.getValues().add(value);
      }

   }

   private void setMergeUpdateItem(SQLExpr valueExpr, SQLObject parent) {
      SQLMergeStatement.MergeUpdateClause clause = (SQLMergeStatement.MergeUpdateClause)parent;
      SQLUpdateSetItem item = (SQLUpdateSetItem)clause.getItems().get(0);

      for(int i = 0; i < clause.getItems().size(); ++i) {
         if (((SQLUpdateSetItem)clause.getItems().get(i)).getValue() == valueExpr) {
            item = (SQLUpdateSetItem)clause.getItems().get(i);
            break;
         }
      }

      ValueMemo value = this.getValueMemo(item.getColumn(), valueExpr);
      value.ref = valueExpr;
      value.expr = parent;
      value.value = this.getValue(valueExpr);
      value.isPreDefined = value.toString().equals("?");
      value.operator = "SET";
      this.scope.getValues().add(value);
   }

   private void setUpdateItem(SQLExpr valueExpr, SQLObject parent) {
      SQLUpdateSetItem item = (SQLUpdateSetItem)parent;
      ValueMemo value = this.getValueMemo(item.getColumn(), valueExpr);
      value.ref = valueExpr;
      value.expr = parent;
      value.value = this.getValue(valueExpr);
      value.isPreDefined = value.toString().equals("?");
      value.operator = "SET";
      this.scope.getValues().add(value);
   }

   private void setInSubQuery(SQLExpr valueExpr, SQLObject parent) {
      ValueMemo value = this.getValueMemo((SQLExpr)null, valueExpr);
      value.ref = valueExpr;
      value.expr = parent;
      value.value = this.getValue(valueExpr);
      value.operator = "IN";
      this.scope.getValues().add(value);
   }

   private void setLimit(SQLExpr valueExpr, SQLObject parent) {
      SQLLimit limit = (SQLLimit)parent;
      ValueMemo value;
      FieldMemo field;
      if (limit.getOffset() != null && limit.getOffset() == valueExpr) {
         value = new ValueMemo();
         value.ref = limit.getOffset();
         value.expr = parent;
         value.value = this.getValue(valueExpr);
         value.isPreDefined = valueExpr.toString().equals("?");
         value.operator = "LIMIT";
         field = new FieldMemo();
         field.name = parent + "limit_offset";
         value.field = field;
         this.scope.getValues().add(value);
      }

      if (limit.getRowCount() != null && limit.getRowCount() == valueExpr) {
         value = new ValueMemo();
         value.ref = limit.getRowCount();
         value.expr = parent;
         value.value = this.getValue(valueExpr);
         value.isPreDefined = valueExpr.toString().equals("?");
         value.operator = "LIMIT";
         field = new FieldMemo();
         field.name = parent + "limit_rowcount";
         value.field = field;
         this.scope.getValues().add(value);
      }

   }

   private void setBetween(SQLExpr valueExpr, SQLObject parent) {
      SQLBetweenExpr between = (SQLBetweenExpr)parent;
      SQLExpr expr = valueExpr == between.getBeginExpr() ? between.getBeginExpr() : between.getEndExpr();
      ValueMemo value = this.getValueMemo(expr, valueExpr);
      value.ref = valueExpr;
      value.expr = parent;
      value.value = this.getValue(valueExpr);
      value.isPreDefined = valueExpr.toString().equals("?");
      value.operator = "BETWEEN";
      this.scope.getValues().add(value);
   }

   private ValueMemo getValueMemo(SQLExpr x, SQLExpr valueExpr) {
      return this.getValueMemo(x, valueExpr, false);
   }

   private ValueMemo getValueMemo(SQLExpr x, SQLExpr valueExpr, boolean nullIfNoField) {
      Scope current = this.scope.getCurrent();
      if (current.getFieldMap().isEmpty() && !current.getChildren().isEmpty()) {
         current = (Scope)current.getChildren().get(0);
      }

      ValueMemo value = current.getFieldValueInfo(x);
      if (value == null && !nullIfNoField) {
         value = new ValueMemo(valueExpr);
         FieldMemo field = new FieldMemo();
         field.name = this.alias.aliasField();
         value.field = field;
      }

      return value;
   }

   private void setOther(SQLExpr valueExpr, SQLObject parent) {
      ValueMemo value = this.getValueMemo((SQLExpr)null, valueExpr);
      value.ref = valueExpr;
      value.expr = parent;
      value.value = this.getValue(valueExpr);
      value.operator = "COMPLEX";
      this.scope.getValues().add(value);
   }

   private Object getValue(SQLExpr value) {
      if (value instanceof SQLNullExpr) {
         return "NULL";
      } else {
         return value instanceof SQLValuableExpr ? ((SQLValuableExpr)value).getValue() : value.toString();
      }
   }

   public boolean visit(SQLTimestampExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLNumberExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLDateExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLCharExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLNCharExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLIntegerExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLBigIntExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLBooleanExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLDateTimeExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLBinaryExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLDecimalExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLDoubleExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLFloatExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLHexExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLJSONExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLRealExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLSmallIntExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLTimeExpr x) {
      this.setValue(x);
      return true;
   }

   public boolean visit(SQLTinyIntExpr x) {
      this.setValue(x);
      return true;
   }
}