package de.brightbyte.db;

import java.sql.SQLException;

import de.brightbyte.data.cursor.ColumnDataCursor;
import de.brightbyte.data.cursor.DataRow;
import de.brightbyte.job.Progress;
import de.brightbyte.job.Progress.Listener;
import de.brightbyte.util.PersistenceException;

public class DataPump<T> implements Progress.Source {
	protected String name;
	
	protected String[] columns;
	protected ColumnDataCursor source;
	protected Inserter drain;
	
	protected long total = -1;
	protected Progress.State progress;
	
	public void run() throws PersistenceException {
		try {
			if (progress!=null) progress.fireStart(total);
			
			DataRow row;
			while ( (row = source.next()) != null ) {
				for (String col: columns) {
					Object v = row.getObject(col);
					drain.updateObject(col, v);
				}
				
				drain.updateRow();
				if (progress!=null) progress.fireStep(1);
			}
			
			if (progress!=null) progress.fireDone(total);
		} catch (SQLException e) {
			if (progress!=null) progress.fireFailed(e);
			throw new PersistenceException(e);			
		} catch (PersistenceException e) {
			if (progress!=null) progress.fireFailed(e);
			throw e;			
		} catch (RuntimeException e) {
			if (progress!=null) progress.fireFailed(e);
			throw e;			
		} finally {
			if (progress!=null && !progress.isTerminated()) progress.fireFailed(null);
		}
	}
	
	public void addProgressListener(Listener li) {
		if (progress==null) progress = new Progress.State(this, name);
		progress.addProgressListener(li);
	}

	public void removeProgressListener(Listener li) {
		if (progress!=null) progress.removeProgressListener(li);
	}

}