package hirondelle.predict.main.codes;
import java.util.*;
import java.util.logging.*;
import javax.servlet.ServletContext;
import hirondelle.web4j.model.Id;
import hirondelle.web4j.database.DAOException;
import hirondelle.web4j.database.SqlId;
import hirondelle.web4j.database.Db;
import hirondelle.web4j.util.Util;
import hirondelle.web4j.model.Code;
public final class CodeTableUtil {
public static final SqlId FETCH_OUTCOME_CODES = new SqlId("FETCH_OUTCOME_CODES");
public static void init(ServletContext aContext) throws DAOException {
fLogger.fine("Fetching code tables.");
fContext = aContext;
fAllCodeTables = new LinkedHashMap<CodeTable, Map<Id, Code>>();
for(CodeTable codeTable: CodeTable.values()){
fetchAndRememberCodeTable(codeTable);
placeInAppScope(codeTable);
}
}
static Code populate(Id aCodeId, CodeTable aCodeTable){
Code result = null;
Map<Id, Code> codeTable = fAllCodeTables.get(aCodeTable);
if ( codeTable == null ){
throw new RuntimeException("Cannot populate item. Unknown code table " + Util.quote(aCodeTable));
}
if ( aCodeId != null ){
result = codeTable.get(aCodeId);
if ( result == null ){
throw new RuntimeException("Cannot find item in code table " + Util.quote(aCodeTable) + " using Id: " + Util.quote(aCodeId));
}
}
return result;
}
private static Map<CodeTable, Map<Id, Code>> fAllCodeTables;
private static ServletContext fContext;
private static final Logger fLogger = Util.getLogger(CodeTableUtil.class);
private static void fetchAndRememberCodeTable(CodeTable aCodeTable) throws DAOException {
Map<Id, Code> codeTable = null;
if ( CodeTable.OUTCOMES == aCodeTable ){
codeTable = getCodes(FETCH_OUTCOME_CODES);
}
else {
throw new AssertionError("CodeTable not known to CodeTableUtil : " + aCodeTable);
}
fLogger.fine("Code Table " + Util.quote(aCodeTable) + ": " + Util.logOnePerLine(codeTable));
fAllCodeTables.put(aCodeTable, codeTable);
}
private static Map<Id, Code> getCodes(SqlId aSqlId) throws DAOException {
Map<Id, Code> result = new LinkedHashMap<Id, Code>();
List<Code> codes = Db.list(Code.class, aSqlId);
result = Util.asMap(codes, Id.class, "getId");
return result;
}
private static void placeInAppScope(CodeTable aCodeTable){
Map<Id, Code> codeTable = fAllCodeTables.get(aCodeTable);
Collection<Code> codeValues = codeTable.values();
fContext.setAttribute(aCodeTable.getTableName().toString(), codeValues);
}
}