/*
 * $Id: InterbaseSQLParser.java,v 1.1 2004/11/19 13:59:45 koppy Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 * Created on 15.11.2004
 *
 * $Log: InterbaseSQLParser.java,v $
 * Revision 1.1  2004/11/19 13:59:45  koppy
 * Auf Interbase/Firebird SQL-Parser.
 *
 */
package vkc.db.helper;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * This class represents
 * @author Andreas Koop
 */
public class InterbaseSQLParser {

	private List stmts = new ArrayList();
	private File file = null; 
	private boolean removeStmtLimiter = true;
	private boolean debug = false;
	
	public InterbaseSQLParser(String ddlFile){
		
	    this.file = new File(ddlFile);
	}
	
	/**
	 * Parses the SQL-File und returns a list
	 * of the contained statements.
	 * @return
	 * @throws IOException
	 */
	public List parseSQLFile() throws IOException {
	    
	    if(!stmts.isEmpty())
	        return stmts;
	    
	    BufferedInputStream bis = new BufferedInputStream( new FileInputStream( file ) );
		
		int ch;
		StringBuffer buffer = new StringBuffer();
		
		while ( ( ch = bis.read() ) != -1 ) {	
			buffer.append( (char)ch );
			
			// Kommentare rausfiltern
			if ( buffer.toString().indexOf( "/*" ) > -1 ) {
				if ( buffer.toString().indexOf( "*/" ) > -1 ) {
					buffer.delete( 0, buffer.length() );
				}
				
				continue;
			}
			
			if(buffer.toString().trim().length() == 0){
			    buffer.delete( 0, buffer.length() );
			    continue;
			}
			
			String s = buffer.toString().trim(); 
			if ( !s.endsWith( ";" ) ) {
				continue;
			}
			
			if(removeStmtLimiter){
			    s = s.substring(0, s.length()-1);
			}
			    
			
			if(debug)
			    System.out.println("S=" + s);
			stmts.add(s);
			
			buffer.delete( 0, buffer.length() );
		}
		
		bis.close();

		return stmts;
	}
	
	/**
	 * Returns the SQL-File object
	 * 
	 * @return
	 */
    public File getFile() {
        return file;
    }
    public boolean isRemoveStmtLimiter() {
        return removeStmtLimiter;
    }
    public void setRemoveStmtLimiter(boolean removeStmtLimiter) {
        this.removeStmtLimiter = removeStmtLimiter;
    }
    public boolean isDebug() {
        return debug;
    }
    public void setDebug(boolean debug) {
        this.debug = debug;
    }
	
	public static void main( String[] args ) {
	    
	    InterbaseSQLParser parser = new InterbaseSQLParser( "db/dbschema/scripts/interbase/vkc_db_interbase_setup.sql" );
	    parser.setDebug(true);
	    
	    try {
            parser.parseSQLFile( );
        } catch (IOException e) {
            e.printStackTrace();
        }
		
	}
	

}
