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

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

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;

public class InsertionHashInfoDAO extends AbstractDAO {
    Logger _log = Logger.getLogger(InsertionHashInfoDAO.class);
	
	public InsertionHashInfoDAO(TransactionManager transactionManager)
			throws SQLException {
		super(transactionManager);
	}
	
	public boolean insert(int fileId, byte[] digest) throws SQLException {
	    if (exists(fileId)) {
	        String message = "ID '" + fileId + "' has been already registered.";
	        _log.warn(message);
	        return false;
	    }
		PreparedStatement pstmt = null;
		// create sql
		String sql = "insert into " + TableType.HASH_INFO + " values (?,?)";
		// prepare the statement
		pstmt = prepareStatement(sql);
		pstmt.setInt(1, fileId);
		pstmt.setBytes(2, digest);
		// execute query
		if (executeUpdate(pstmt) == 1) {
			return true;
		}
		return false;
	}
	
	private boolean exists(int fileId) throws SQLException {
        ColumnName[] columns = {ColumnName.ID};
        String sql = SQLGenerator.getWhereSelectStatement(TableType.HASH_INFO, columns, ColumnName.ID, String.valueOf(fileId));
        PreparedStatement pstmt = prepareStatement(sql);
        ResultSet results = executeQuery(pstmt);
        if (!results.next()) {
            return false;
        }
        
        return true;
	}
}
