package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

@Exercice(3)
public class Table {
    private String name;
    private String[] fields;
    private SQLType[] types;
    private String[] constraints;
    private String[] properties;
    private Connection co;
    
    public Table(Connection co,
    		      String name,
    		      String[] fields,
    		      SQLType[] types,
    		      String[] constraints,
    		      String[] properties){
    	/* fields, type and constraints must have the same length */
            this.name=name;
            this.fields=fields;
            this.types=types;
            this.constraints=constraints;
            this.properties=properties;
            this.co =co;
    }
    
    public void init(){
    	StringBuffer sb = new StringBuffer("CREATE TABLE "+name+ "(");
    	for(int i=0; i< fields.length; i++){
    		if(i!=0) sb.append(", ");
    		sb.append("\""+fields[i]+"\" "+types[i]+" "+constraints[i]);
    	}
    	for(String p : properties){
    		sb.append(", ");
    		sb.append(p);
    	}
    	System.out.println(sb);
    	try {
    		Statement st = co.createStatement();
			st.executeUpdate(sb.toString());
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
    
    @Exercice(4)
    public void drop(){
    	try {
    		Statement st = co.createStatement();
			st.executeUpdate("DROP TABLE "+name);
		} catch (SQLException e) {
			e.printStackTrace();
		}
   }
   
    @Exercice(4)
    public String toString(){
        StringBuffer sb=new StringBuffer();
        String str="                           ";
        try {
        	Statement st = co.createStatement();
        	String s="SELECT * FROM "+name;
        	ResultSet rs=st.executeQuery(s);
        	ResultSetMetaData rsmd = rs.getMetaData();
        	int c = rsmd.getColumnCount();
        	for(int i=0;i < c; i++){
        		String k=rsmd.getCatalogName(i);
        		sb.append(" | "+k+str.substring(k.length()));
        	}
        	sb.append('\n');
        	while(rs.next()){
        		for(int i=0;i < c; i++){
        			String k=rs.getObject(i).toString();
        			sb.append(" | "+k+str.substring(k.length()));
        		}
        		sb.append('\n');
        	}
        } catch (SQLException e) {
        	e.printStackTrace();
        }
        return sb.toString();
    }
    
}
