package com.chenyang.druid.sql.ast;

import com.chenyang.druid.sql.ast.statement.SQLSelectOrderByItem;
import com.chenyang.druid.sql.visitor.SQLASTVisitor;
import java.util.ArrayList;
import java.util.List;

public final class SQLOrderBy extends SQLObjectImpl implements SQLReplaceable {
   protected final List<SQLSelectOrderByItem> items = new ArrayList();
   private boolean sibings;

   public SQLOrderBy() {
   }

   public SQLOrderBy(SQLExpr expr) {
      SQLSelectOrderByItem item = new SQLSelectOrderByItem(expr);
      this.addItem(item);
   }

   public SQLOrderBy(SQLExpr expr, SQLOrderingSpecification type) {
      SQLSelectOrderByItem item = new SQLSelectOrderByItem(expr, type);
      this.addItem(item);
   }

   public void addItem(SQLSelectOrderByItem item) {
      if (item != null) {
         item.setParent(this);
      }

      this.items.add(item);
   }

   public void addItem(SQLExpr item) {
      this.addItem(new SQLSelectOrderByItem(item));
   }

   public List<SQLSelectOrderByItem> getItems() {
      return this.items;
   }

   public boolean isSibings() {
      return this.sibings;
   }

   public void setSibings(boolean sibings) {
      this.sibings = sibings;
   }

   protected void accept0(SQLASTVisitor v) {
      if (v.visit(this)) {
         for(int i = 0; i < this.items.size(); ++i) {
            SQLSelectOrderByItem item = (SQLSelectOrderByItem)this.items.get(i);
            item.accept(v);
         }
      }

      v.endVisit(this);
   }

   public boolean equals(Object o) {
      if (this == o) {
         return true;
      } else if (o != null && this.getClass() == o.getClass()) {
         SQLOrderBy order = (SQLOrderBy)o;
         return this.sibings != order.sibings ? false : this.items.equals(order.items);
      } else {
         return false;
      }
   }

   public int hashCode() {
      int result = this.items.hashCode();
      result = 31 * result + (this.sibings ? 1 : 0);
      return result;
   }

   public void addItem(SQLExpr expr, SQLOrderingSpecification type) {
      SQLSelectOrderByItem item = this.createItem();
      item.setExpr(expr);
      item.setType(type);
      this.addItem(item);
   }

   public boolean replace(SQLExpr expr, SQLExpr target) {
      for(SQLSelectOrderByItem item : this.items) {
         if (item.replace(expr, target)) {
            return true;
         }
      }

      return false;
   }

   protected SQLSelectOrderByItem createItem() {
      return new SQLSelectOrderByItem();
   }

   public SQLOrderBy clone() {
      SQLOrderBy x = new SQLOrderBy();

      for(SQLSelectOrderByItem item : this.items) {
         SQLSelectOrderByItem item1 = item.clone();
         item1.setParent(x);
         x.items.add(item1);
      }

      x.sibings = this.sibings;
      return x;
   }
}
