package com.chenyang.druid.sql.ast.statement;

import com.chenyang.druid.FastsqlException;
import com.chenyang.druid.sql.ast.SQLHint;
import com.chenyang.druid.sql.visitor.SQLASTVisitor;
import java.io.IOException;

public class SQLUnionQueryTableSource extends SQLTableSourceImpl {
   private SQLUnionQuery union;

   public SQLUnionQueryTableSource() {
   }

   public SQLUnionQueryTableSource(String alias) {
      super(alias);
   }

   public SQLUnionQueryTableSource(SQLUnionQuery union, String alias) {
      super(alias);
      this.setUnion(union);
   }

   public SQLUnionQueryTableSource(SQLUnionQuery union) {
      this.setUnion(union);
   }

   protected void accept0(SQLASTVisitor visitor) {
      if (visitor.visit(this) && this.union != null) {
         this.union.accept(visitor);
      }

      visitor.endVisit(this);
   }

   public void output(Appendable buf) {
      try {
         buf.append("(");
         this.union.output(buf);
         buf.append(")");
      } catch (IOException ex) {
         throw new FastsqlException("output error", ex);
      }
   }

   public SQLUnionQuery getUnion() {
      return this.union;
   }

   public void setUnion(SQLUnionQuery union) {
      if (union != null) {
         union.setParent(this);
      }

      this.union = union;
   }

   public SQLUnionQueryTableSource clone() {
      SQLUnionQueryTableSource x = new SQLUnionQueryTableSource(this.union.clone(), this.alias);
      if (this.flashback != null) {
         x.setFlashback(this.flashback.clone());
      }

      if (this.hints != null) {
         for(SQLHint e : this.hints) {
            SQLHint e2 = e.clone();
            e2.setParent(x);
            x.getHints().add(e2);
         }
      }

      return x;
   }

   public boolean equals(Object o) {
      if (this == o) {
         return true;
      } else if (o != null && this.getClass() == o.getClass()) {
         SQLUnionQueryTableSource that = (SQLUnionQueryTableSource)o;
         return this.union != null ? this.union.equals(that.union) : that.union == null;
      } else {
         return false;
      }
   }

   public int hashCode() {
      return this.union != null ? this.union.hashCode() : 0;
   }

   public SQLTableSource findTableSourceWithColumn(long columnNameHash, String columnName, int option) {
      if (this.union == null) {
         return null;
      } else {
         SQLSelectQueryBlock firstQueryBlock = this.union.getFirstQueryBlock();
         if (firstQueryBlock != null) {
            SQLSelectItem selectItem = firstQueryBlock.findSelectItem(columnNameHash);
            if (selectItem != null) {
               return this;
            }
         }

         return null;
      }
   }
}
