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

import com.chenyang.druid.sql.ast.SQLDataType;
import com.chenyang.druid.sql.ast.SQLExprImpl;
import com.chenyang.druid.sql.ast.SQLObject;
import com.chenyang.druid.sql.ast.statement.SQLSelect;
import com.chenyang.druid.sql.ast.statement.SQLSelectItem;
import com.chenyang.druid.sql.ast.statement.SQLSelectQueryBlock;
import com.chenyang.druid.sql.visitor.SQLASTVisitor;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;

public class SQLQueryExpr extends SQLExprImpl implements Serializable {
   private static final long serialVersionUID = 1L;
   public SQLSelect subQuery;

   public SQLQueryExpr() {
   }

   public SQLQueryExpr(SQLSelect select) {
      this.setSubQuery(select);
   }

   public SQLSelect getSubQuery() {
      return this.subQuery;
   }

   public void setSubQuery(SQLSelect subQuery) {
      if (subQuery != null) {
         subQuery.setParent(this);
      }

      this.subQuery = subQuery;
   }

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

      visitor.endVisit(this);
   }

   public List<SQLObject> getChildren() {
      return Collections.singletonList(this.subQuery);
   }

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

   public boolean equals(Object obj) {
      if (this == obj) {
         return true;
      } else if (obj == null) {
         return false;
      } else if (this.getClass() != obj.getClass()) {
         return false;
      } else {
         SQLQueryExpr other = (SQLQueryExpr)obj;
         if (this.subQuery == null) {
            if (other.subQuery != null) {
               return false;
            }
         } else if (!this.subQuery.equals(other.subQuery)) {
            return false;
         }

         return true;
      }
   }

   public SQLQueryExpr clone() {
      SQLQueryExpr x = new SQLQueryExpr();
      if (this.subQuery != null) {
         x.setSubQuery(this.subQuery.clone());
      }

      return x;
   }

   public SQLDataType computeDataType() {
      if (this.subQuery == null) {
         return null;
      } else {
         SQLSelectQueryBlock queryBlock = this.subQuery.getFirstQueryBlock();
         if (queryBlock == null) {
            return null;
         } else {
            List<SQLSelectItem> selectList = queryBlock.getSelectList();
            return selectList.size() == 1 ? ((SQLSelectItem)selectList.get(0)).computeDataType() : null;
         }
      }
   }
}
