package com.alibaba.druid.sql.repository;

import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition;
import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement;
import com.alibaba.druid.sql.ast.statement.SQLTableElement;
import com.alibaba.druid.sql.ast.statement.SQLUniqueConstraint;
import com.alibaba.druid.util.FnvHash;

public class SchemaObject {
   private final Schema schema;
   private final String name;
   private final long hashCode64;
   private final SchemaObjectType type;
   private SQLStatement statement;
   private long rowCount;

   protected SchemaObject(Schema schema, String name, SchemaObjectType type) {
      this(schema, name, type, (SQLStatement)null);
   }

   protected SchemaObject(Schema schema, String name, SchemaObjectType type, SQLStatement statement) {
      this.rowCount = -1L;
      this.schema = schema;
      this.name = name;
      this.type = type;
      this.statement = statement;
      this.hashCode64 = FnvHash.hashCode64(name);
   }

   public SchemaObject clone() {
      SchemaObject x = new SchemaObject(this.schema, this.name, this.type);
      if (this.statement != null) {
         x.statement = this.statement.clone();
      }

      x.rowCount = this.rowCount;
      return x;
   }

   public long nameHashCode64() {
      return this.hashCode64;
   }

   public SQLStatement getStatement() {
      return this.statement;
   }

   public SQLColumnDefinition findColumn(String columName) {
      long hash = FnvHash.hashCode64(columName);
      return this.findColumn(hash);
   }

   public SQLColumnDefinition findColumn(long columNameHash) {
      if (this.statement == null) {
         return null;
      } else {
         return this.statement instanceof SQLCreateTableStatement ? ((SQLCreateTableStatement)this.statement).findColumn(columNameHash) : null;
      }
   }

   public boolean matchIndex(String columnName) {
      if (this.statement == null) {
         return false;
      } else if (this.statement instanceof SQLCreateTableStatement) {
         SQLTableElement index = ((SQLCreateTableStatement)this.statement).findIndex(columnName);
         return index != null;
      } else {
         return false;
      }
   }

   public boolean matchKey(String columnName) {
      if (this.statement == null) {
         return false;
      } else if (this.statement instanceof SQLCreateTableStatement) {
         SQLTableElement index = ((SQLCreateTableStatement)this.statement).findIndex(columnName);
         return index instanceof SQLUniqueConstraint;
      } else {
         return false;
      }
   }

   public String getName() {
      return this.name;
   }

   public SchemaObjectType getType() {
      return this.type;
   }

   public long getRowCount() {
      return this.rowCount;
   }

   public Schema getSchema() {
      return this.schema;
   }

   public static enum Type {
      Sequence,
      Table,
      View,
      Index,
      Function;
   }
}
