/********************************************************************
 * Copyright © 2007 VHA. All rights reserved
 ********************************************************************/

package gov.va.med.fw.persistent.hibernate;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.Validate;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Table;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

import gov.va.med.fw.service.AbstractComponent;

/**
 * Initial javadoc for class TableAndColumnsUtil. TODO - Add content here
 * 
 * Created May 18, 2007 2:18:55 PM
 * 
 * @author DNS   BOHMEG
 */
public class TableAndColumnUtils extends AbstractComponent {
	private LocalSessionFactoryBean sessionFactory;
	private Map<String, Set> tableAndMappedColumns;

	public Set getTableColumns(String table) {
		return tableAndMappedColumns.get(table);
	}

	public Map<String, Set> getAllTableColumns() {
		return tableAndMappedColumns;
	}

	public void afterPropertiesSet() {
		Validate.notNull(sessionFactory, "sessionFactory is required");

		/*
		 * since the current History implementation deals with
		 * including/excluding columns from the various history tables (key
		 * point here is that the entry point is the table name, not the
		 * persistent class name), then let's cache (as a Map) the columns from
		 * the tables here once so we do not have to iterate through each time
		 */
		Configuration hibernateHistoryConfiguration = sessionFactory.getConfiguration();
		tableAndMappedColumns = new HashMap<String, Set>();
		Table table = null;
		Set<String> tableColumns = new HashSet<String>();
		for (Iterator<Table> itr = hibernateHistoryConfiguration.getTableMappings(); itr.hasNext();) {
			tableColumns.clear();
			table = itr.next();
			// build the columns into a List
			for (Iterator<Column> itr2 = table.getColumnIterator(); itr2.hasNext();) {
				tableColumns.add(itr2.next().getName());
			}
			tableAndMappedColumns.put(table.getName(), new HashSet<String>(tableColumns));
		}
	}

	public LocalSessionFactoryBean getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(LocalSessionFactoryBean sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
