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

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jp.ac.osaka_u.ist.sel.similarity.fileclone.database.CloneRegisterDAOManager;
import jp.ac.osaka_u.ist.sel.similarity.fileclone.database.InsertionCloneInfoDAO;
import jp.ac.osaka_u.ist.sel.similarity.fileclone.database.SelectionHashDAO;

import org.apache.log4j.Logger;

/**
 * Insert group id to the CloneInfo table.
 *  
 * @author ysk-ssk
 *
 */

/*
 * Get file sets from FILE_INFO, which have the same MD5 value,
 * and input them into the database.
 */
public class CloneInfoRegister {
	private Logger _log = Logger.getLogger("CloneInfoRegister");
    private final InsertionCloneInfoDAO _filecloneDAO;
    private final SelectionHashDAO _hashDAO;

	public CloneInfoRegister(CloneRegisterDAOManager daoManager) throws SQLException {
	    _hashDAO = daoManager.getHashDAO();
        _filecloneDAO = daoManager.getFileCloneDAO();
	}
	
	public void execute() throws Exception {
		Map<List<Byte>,Set<Integer>> fileIdToHashValue = _hashDAO.getHashToIdMapping();
		
		int groupId = 1;
		for (List<Byte> hash : fileIdToHashValue.keySet()) {
		    Set<Integer> files = fileIdToHashValue.get(hash);
		    if (files.size() < 2) {
		        continue;
		    }
		    for (Integer fileId : files) {
	            registerCloneInfo(fileId,groupId);
		    }
		    groupId++;
		}
		
	}
	
	private void registerCloneInfo(int fileId, int groupId) throws SQLException {
		if (!_filecloneDAO.insertData(fileId, groupId)) {
		    _log.error("Failed to register: " + fileId);
		}
	}
	
}
