package util.sqlparse.visitor.sqlserver.visitor;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelectGroupByClause;
import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock;
import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement;
import com.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerSelectQueryBlock;
import com.alibaba.druid.sql.dialect.sqlserver.ast.stmt.SQLServerDeleteStatement;
import com.alibaba.druid.sql.dialect.sqlserver.ast.stmt.SQLServerUpdateStatement;
import com.alibaba.druid.sql.dialect.sqlserver.visitor.DefaultSQLServerASTVisitor;
import java.util.ArrayList;
import java.util.List;

public class WhereVisitor extends DefaultSQLServerASTVisitor {
   private boolean debug = false;
   private List<String> wheres = new ArrayList();

   public List<String> getWheres() {
      return this.wheres;
   }

   public void perform(List<SQLStatement> statements) {
      if (statements != null && statements.size() != 0) {
         for(SQLStatement statement : statements) {
            statement.accept(this);
         }

      }
   }

   public boolean visit(SQLUpdateStatement x) {
      SQLExpr where = x.getWhere();
      if (where != null) {
         this.wheres.add(where.toString());
      }

      return true;
   }

   public boolean visit(SQLServerUpdateStatement x) {
      SQLExpr where = x.getWhere();
      if (where != null) {
         this.wheres.add(where.toString());
      }

      return true;
   }

   public boolean visit(SQLDeleteStatement x) {
      SQLExpr where = x.getWhere();
      if (where != null) {
         this.wheres.add(where.toString());
      }

      return true;
   }

   public boolean visit(SQLServerDeleteStatement x) {
      SQLExpr where = x.getWhere();
      if (where != null) {
         this.wheres.add(where.toString());
      }

      return true;
   }

   public boolean visit(SQLServerSelectQueryBlock x) {
      SQLExpr where = x.getWhere();
      if (where != null) {
         this.wheres.add(where.toString());
      }

      SQLSelectGroupByClause groupBy = x.getGroupBy();
      if (groupBy != null && groupBy.getHaving() != null) {
         this.wheres.add(groupBy.getHaving().toString());
      }

      return true;
   }

   public boolean visit(SQLSelectQueryBlock x) {
      SQLExpr where = x.getWhere();
      if (where != null) {
         this.wheres.add(where.toString());
      }

      SQLSelectGroupByClause groupBy = x.getGroupBy();
      if (groupBy != null && groupBy.getHaving() != null) {
         this.wheres.add(groupBy.getHaving().toString());
      }

      return true;
   }
}
