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

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
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 information of applications.
 * 
 * @author ysk-ssk
 *
 */
public class InsertionDomainDAO extends AbstractDAO {
	private int _maxId = 1;// current max Id number in AppDAO database.
	private Map<String,Integer> _domainToIdMapping = new HashMap<String,Integer>();// cache

	public InsertionDomainDAO(TransactionManager transactionManager)
			throws SQLException {
		super(transactionManager);
		initializeNameToIdMapping();
	}
	
	private void initializeNameToIdMapping() throws SQLException {
		ColumnName[] columns = {ColumnName.ID,ColumnName.NAME};
		String sql = SQLGenerator.getSelectStatement(TableType.DOMAIN_INFO,columns);
		PreparedStatement pstmt = prepareStatement(sql);
		ResultSet results = executeQuery(pstmt);
		while (results.next()) {
			_domainToIdMapping.put(results.getString(2),results.getInt(1));
		}
		_maxId = getMaxId();
		if (_maxId != -1) {
			_maxId += 1;
		} else {
			_maxId = 1;
		}
	}
	
	private int getMaxId() throws SQLException {
		String sql = SQLGenerator.getSelectMaxStatement(TableType.DOMAIN_INFO,ColumnName.ID);
		return getIntegerValue(executeQuery(prepareStatement(sql))); 
	}
	
	public int getId(String name) {
		Integer id = _domainToIdMapping.get(name);
		if (id == null) {
			return -1;
		}
		return id;
	}

	/**
	 * Insert following data:
	 * 
	 * * project root path
	 * 
	 * @param domainName
	 * @param numberOfFile
	 * @param appSize
	 * @return
	 * @throws SQLException
	 */
	public boolean insert(String domainName) throws SQLException {
        // avoid duplicated register
		Set<String> domainNameSet = _domainToIdMapping.keySet();
		if (domainNameSet != null && domainNameSet.contains(domainName)) {
			return true;
		}
		String sql = "";
		PreparedStatement pstmt = null;
		sql = "insert into " + TableType.DOMAIN_INFO + " values (?,?)";
		pstmt = prepareStatement(sql);
		pstmt.setInt(1, _maxId);// ID
		pstmt.setString(2, domainName);// path
		if (executeUpdate(pstmt) == 1) {
			_domainToIdMapping.put(domainName, _maxId++);
			return true;
		}
		return false;
	}
	

}
