package org.seamframework.sql;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Update<X> extends AbstractStatement<X> {
	
	private Expression<Boolean> where;
	private final From<X> from;

	public Update(Table<X> table) {
		super(table);
		from = new From<X>(table);
	}

	public <Y> Expression<Y> get(Column<X,Y> column) {
		return from.get(column);
	}

	public void where(Expression<Boolean> where) {
		this.where = where;
	}
	
	@Override
	public List<Parameter<?>> getParameters() {
		List<Parameter<?>> list = new ArrayList<Parameter<?>>();
		list.addAll( super.getParameters() );
		list.addAll( where.getParameters() );
		return list;
	}
	
	@Override
	public String toSql() {
		StringBuilder sql = new StringBuilder();
		sql.append("update ");
		sql.append( table.getQualifiedName() );
		sql.append(" set ");
		for (Iterator<Column<X, ?>> i =  columns.iterator(); i.hasNext(); ) {
			sql.append( i.next().getName() );
			sql.append("=?");
			if ( i.hasNext() ) sql.append(", ");
		}
		if (where!=null) {
			sql.append(" where ");
			sql.append( where.toSql() );
		}
		return sql.toString();
	}
}
