package com.chenyang.nse.bussiness.entity.db;

import com.chenyang.nse.bussiness.enumeration.EdbType;
import com.chenyang.nse.bussiness.tools.jdbc.JdbcTool;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class TableInfo {
   private String tablecat;
   private String tableschem;
   private String tablename;
   private String tabletype;
   private String remarks;
   private String typecat;
   private String typeschem;
   private String typename;
   private String selfreferencingcolname;
   private String refgeneration;
   private String dbcode;
   private List<ColumnInfo> columninfos;

   public TableInfo() {
   }

   public TableInfo(String tablecat, String tableschem, String tablename, String tabletype, String remarks, String typecat, String typeschem, String typename, String selfreferencingcolname, String refgeneration) {
      this.tablecat = tablecat;
      this.tableschem = tableschem;
      this.tablename = tablename;
      this.tabletype = tabletype;
      this.remarks = remarks;
      this.typecat = typecat;
      this.typeschem = typeschem;
      this.typename = typename;
      this.selfreferencingcolname = selfreferencingcolname;
      this.refgeneration = refgeneration;
   }

   public String getTablecat() {
      return this.tablecat;
   }

   public void setTablecat(String tablecat) {
      this.tablecat = tablecat;
   }

   public String getTableschem() {
      return this.tableschem;
   }

   public void setTableschem(String tableschem) {
      this.tableschem = tableschem;
   }

   public String getTablename() {
      return this.tablename;
   }

   public void setTablename(String tablename) {
      this.tablename = tablename;
   }

   public String getTabletype() {
      return this.tabletype;
   }

   public void setTabletype(String tabletype) {
      this.tabletype = tabletype;
   }

   public String getRemarks() {
      return this.remarks;
   }

   public void setRemarks(String remarks) {
      this.remarks = remarks;
   }

   public String getTypecat() {
      return this.typecat;
   }

   public void setTypecat(String typecat) {
      this.typecat = typecat;
   }

   public String getTypeschem() {
      return this.typeschem;
   }

   public void setTypeschem(String typeschem) {
      this.typeschem = typeschem;
   }

   public String getTypename() {
      return this.typename;
   }

   public void setTypename(String typename) {
      this.typename = typename;
   }

   public String getSelfreferencingcolname() {
      return this.selfreferencingcolname;
   }

   public void setSelfreferencingcolname(String selfreferencingcolname) {
      this.selfreferencingcolname = selfreferencingcolname;
   }

   public String getRefgeneration() {
      return this.refgeneration;
   }

   public void setRefgeneration(String refgeneration) {
      this.refgeneration = refgeneration;
   }

   public List<ColumnInfo> getColumninfos() {
      return this.columninfos;
   }

   public void setColumninfos(List<ColumnInfo> columninfos) {
      this.columninfos = columninfos;
   }

   public String getDbcode() {
      return this.dbcode;
   }

   public void setDbcode(String dbcode) {
      this.dbcode = dbcode;
   }

   public String toString() {
      return "TableInfo [tablecat=" + this.tablecat + ", tableschem=" + this.tableschem + ", tablename=" + this.tablename + ", tabletype=" + this.tabletype + ", remarks=" + this.remarks + ", typecat=" + this.typecat + ", typeschem=" + this.typeschem + ", typename=" + this.typename + ", selfreferencingcolname=" + this.selfreferencingcolname + ", refgeneration=" + this.refgeneration + "]";
   }

   public List<TableInfo> getTableInfoByConnection(Connection conn, String schemaPattern, String tableNamePattern) {
      EdbType dbtype = DbInfo.getEdbTypeByConnection(conn);
      String[] types = new String[]{"TABLE"};
      String name = tableNamePattern;
      if (tableNamePattern != null && !"".equals(tableNamePattern)) {
         name = tableNamePattern.replace("%", "");
         tableNamePattern = tableNamePattern.toUpperCase();
      }

      List<TableInfo> list = null;
      if (null == conn) {
         return list;
      } else {
         list = new ArrayList();
         DatabaseMetaData dbmd = null;
         ResultSet rs = null;

         try {
            dbmd = conn.getMetaData();
            rs = dbmd.getTables((String)null, schemaPattern, tableNamePattern, types);

            while(rs.next()) {
               String tablename = rs.getString("TABLE_NAME");
               if (name == null || tablename.contains(name)) {
                  String tablecat = rs.getString("TABLE_CAT");
                  String tableschem = rs.getString("TABLE_SCHEM");
                  String tabletype = rs.getString("TABLE_TYPE");
                  String remarks = rs.getString("REMARKS");
                  String typecat = null;
                  String typeschem = null;
                  String typename = null;
                  String selfreferencingcolname = null;
                  String refgeneration = null;
                  TableInfo temp = new TableInfo(tablecat, tableschem, tablename, tabletype, remarks, typecat, typeschem, typename, selfreferencingcolname, refgeneration);
                  JdbcTool.getColumnInfoInstance();
                  List<ColumnInfo> clist = ColumnInfo.getColumnInfoByConnection(conn, schemaPattern, tablename, (String)null);
                  temp.setColumninfos(clist);
                  temp.setDbcode(dbtype.getDbcode());
                  list.add(temp);
               }
            }
         } catch (SQLException e) {
            e.printStackTrace();
         } finally {
            try {
               if (rs != null) {
                  Statement s = rs.getStatement();
                  rs.close();
                  if (s != null) {
                     s.close();
                  }
               }
            } catch (SQLException e) {
               e.printStackTrace();
            }

         }

         return list;
      }
   }

   public int getTableDataCount(Connection conn, String schema, String tableName) {
      int count = 0;
      String sql = "select count(*) cnt from " + schema + "." + tableName;
      if (schema == null || "".equals(schema)) {
         sql = "select count(*) cnt from " + tableName;
      }

      PreparedStatement pstmt = null;
      ResultSet r = null;

      try {
         pstmt = conn.prepareStatement(sql);

         for(r = pstmt.executeQuery(); r.next(); count = r.getInt("cnt")) {
         }
      } catch (SQLException e1) {
         e1.printStackTrace();
      } finally {
         try {
            if (r != null) {
               r.close();
            }

            if (pstmt != null) {
               pstmt.close();
            }

            if (conn != null) {
               conn.close();
            }
         } catch (SQLException e) {
            e.printStackTrace();
         }

      }

      return count;
   }

   public void deleteTable(Connection conn, String schema, String tableName) {
      String sql = "drop TABLE " + schema + "." + tableName;
      PreparedStatement pstmt = null;

      try {
         pstmt = conn.prepareStatement(sql);
         pstmt.executeUpdate();
      } catch (SQLException e1) {
         e1.printStackTrace();
      } finally {
         try {
            if (pstmt != null) {
               pstmt.close();
            }

            if (conn != null) {
               conn.close();
            }
         } catch (SQLException e) {
            e.printStackTrace();
         }

      }

   }

   public String generateCreateDDL() {
      List<String> primarykey = null;
      StringBuffer create = new StringBuffer();
      String prefix = "CREATE TABLE " + this.getTablename() + " \n (";
      String suffix = "\n )";

      for(ColumnInfo column : this.columninfos) {
         if (create != null && !"".equals(create.toString())) {
            create.append(" ,");
         }

         create.append(column.getColumnname() + " ");
         create.append(column.getTypename() + " ");
         if (column.getColumnsize() != null) {
            create.append("(" + column.getColumnsize() + ") ");
            if (Integer.valueOf(column.getDecimaldigits()) > 0) {
               create.append("," + column.getDecimaldigits());
            }

            create.append(") ");
         }

         if (column.getPrimarykey() != null && column.getPrimarykey().equals("1")) {
            create.append(" NOT NULL ");
            if (primarykey == null) {
               primarykey = new ArrayList();
            }

            primarykey.add(column.getColumnname());
         }
      }

      if (primarykey != null && primarykey.size() > 0) {
         create.append(", PRIMARY KEY (");

         for(int j = 0; j < primarykey.size(); ++j) {
            create.append((String)primarykey.get(j));
            if (j < primarykey.size() - 1) {
               create.append(",");
            }
         }

         create.append(")");
      }

      String sql = prefix + create.toString() + suffix;
      return sql;
   }

   public String generateCreateDDL(String schema, String table) {
      List<String> primarykey = null;
      StringBuffer create = new StringBuffer();
      String prefix = "CREATE TABLE " + schema + "." + table + " \n (";
      String suffix = "\n )";

      for(ColumnInfo column : this.columninfos) {
         if (create != null && !"".equals(create.toString())) {
            create.append(" ,");
         }

         create.append(column.getColumnname() + " ");
         if ("number(p,s)".equals(column.getTypename())) {
            create.append("NUMBER");
         } else {
            create.append(column.getTypename() + " ");
         }

         if ("DATE".equals(column.getTypename())) {
            create.append("");
         } else if ("TIMESTAMP".equals(column.getTypename())) {
            create.append("(" + column.getDecimaldigits() + ") ");
         } else if (column.getColumnsize() != null) {
            create.append("(" + column.getColumnsize() + ") ");
         }

         if (column.getPrimarykey() != null && column.getPrimarykey().equals("1")) {
            create.append(" NOT NULL ");
            if (primarykey == null) {
               primarykey = new ArrayList();
            }

            primarykey.add(column.getColumnname());
         }
      }

      if (primarykey != null && primarykey.size() > 0) {
         create.append(", PRIMARY KEY (");

         for(int j = 0; j < primarykey.size(); ++j) {
            create.append((String)primarykey.get(j));
            if (j < primarykey.size() - 1) {
               create.append(",");
            }
         }

         create.append(")");
      }

      String sql = prefix + create.toString() + suffix;
      return sql;
   }

   public String generateCreateDDLNoConstraint(String schema, String table) {
      List<String> primarykey = null;
      StringBuffer create = new StringBuffer();
      String prefix = "CREATE TABLE " + schema + "." + table + " \n (";
      String suffix = "\n )";

      for(ColumnInfo column : this.columninfos) {
         System.out.println(column.getTypename() + " , " + column.getColumnsize());
         if (create != null && !"".equals(create.toString())) {
            create.append(" ,");
         }

         create.append(column.getColumnname() + " ");
         String typeName = column.getTypename();
         if (typeName.contains("()")) {
            typeName = typeName.replace("()", "(" + column.getColumnsize() + ")");
         }

         create.append(typeName + " ");
         int datatype = Integer.valueOf(column.getDatatype());
         if ((datatype == 12 || datatype == 1 || datatype == -9) && (column.getTypename().toUpperCase().contains("CHAR") || this.dbcode.equalsIgnoreCase(EdbType.DB2.getDbcode()) && column.getTypename().equalsIgnoreCase("VARGRAPHIC"))) {
            create.append("(" + column.getColumnsize());
            create.append(") ");
         }

         if (this.dbcode != null && this.dbcode.equals(EdbType.INFORMIX.getDbcode()) && column.getTypename().toUpperCase().equals("DATETIME")) {
            create.append(" year to fraction ");
         }

         if (!column.getTypename().toUpperCase().contains("FOR BIT DATA")) {
            create.append(" NULL ");
         }
      }

      String sql = prefix + create.toString() + suffix;
      return sql;
   }
}
