package jp.ac.osaka_u.ist.sel.similarity.fileclone.database;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jp.ac.osaka_u.ist.sel.similarity.database.AbstractDAO;
import jp.ac.osaka_u.ist.sel.similarity.database.ColumnName;
import jp.ac.osaka_u.ist.sel.similarity.database.SQLGenerator;
import jp.ac.osaka_u.ist.sel.similarity.database.TableType;
import jp.ac.osaka_u.ist.sel.similarity.database.TransactionManager;

/**
 * DAO class for HashInfo table.
 * Select hash values from HashInfo table.
 * 
 * @author ysk-ssk
 *
 */
public class SelectionHashDAO extends AbstractDAO {
	private Map<List<Byte>,Set<Integer>> _hashToFileIdMapping = new HashMap<List<Byte>,Set<Integer>>();
    // heap size: (32 bit + 32 bit) * n

	public SelectionHashDAO(TransactionManager transactionManager)
			throws SQLException {
		super(transactionManager);
		initializeHashToIdMapping();
	}
	
	/**
	 * Caching file IDs.
	 * 
	 * @throws SQLException
	 */
	private void initializeHashToIdMapping() throws SQLException {
		// create sql
		ColumnName[] columns = {ColumnName.ID,ColumnName.MD5_HASH};
		String sql = SQLGenerator.getSelectStatement(TableType.HASH_INFO, columns);
		// prepare the statement
		PreparedStatement pstmt = prepareStatement(sql);
		// execute
		ResultSet results = executeQuery(pstmt);
		while (results.next()) {
            List<Byte> hashValue = new ArrayList<Byte>();
            for (byte hashElement : results.getBytes(2)) {
                hashValue.add(hashElement);
            }
			int fileId = results.getInt(1);
			Set<Integer> files = _hashToFileIdMapping.get(hashValue);
			if (files == null) {
			    files = new HashSet<Integer>();
			}
			files.add(fileId);
			_hashToFileIdMapping.put(hashValue, files);
		}
	}
	
	public Map<List<Byte>,Set<Integer>> getHashToIdMapping() throws SQLException {
		return _hashToFileIdMapping;
	}
	
}
