package electrosphere.server.db;

import com.google.gson.Gson;
import electrosphere.logger.LoggerInterface;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Result of a single database query
 */
public class DatabaseResult implements Iterable<DatabaseResultRow> {

    boolean isQuery = false;
    boolean isStatement = false;
    boolean succeeded = false;
    boolean hasResultSet = false;
    String code;
    ResultSet rs;
    private static Gson deserializer;
    
    static {
        deserializer = new Gson();
    }
    
    
    protected static DatabaseResult createQuery(String code){
        DatabaseResult rVal = new DatabaseResult();
        rVal.isQuery = true;
        rVal.code = code;
        return rVal;
    }
    
    protected static DatabaseResult createStatement(String code){
        DatabaseResult rVal = new DatabaseResult();
        rVal.isStatement = true;
        rVal.code = code;
        return rVal;
    }
    
    protected void addResultSet(ResultSet rs){
        hasResultSet = true;
        this.rs = rs;
    }
    
    protected ResultSet getResultSet(){
        return rs;
    }
    
    public boolean hasResult(){
        return hasResultSet;
    }
    
    public boolean isQuery(){
        return isQuery;
    }
    
    public boolean isStatement(){
        return isStatement;
    }
    
    public boolean success(){
        return succeeded;
    }
    
    public <T>T deserializeFirstResult(Class<T> className){
        T rVal = null;
        try {
            rs.getString(0);
            rVal = deserializer.fromJson(rs.getString(0), className);
        } catch (SQLException ex) {
            LoggerInterface.loggerFileIO.ERROR("Failure to deserialize result", ex);
        }
        return rVal;
    }
    
    
    public void logRawResult(){
    }

    @Override
    public DatabaseResultIterator iterator() {
        return new DatabaseResultIterator(rs);
    }
}
