@Produces({ MediaType.APPLICATION_JSON })
public JSONObject getPatientStats() {
JSONObject jSONObject = new JSONObject();
PersistenceService persistenceSvc = PersistenceService.getInstance();
Weight latestWeight = null;
Height latestHeight = null;
Boolean calculateBMI = true;
try {
EntityManager em = PersistenceService.getInstance().getEntityManager();
persistenceSvc.beginTx();
Long healthRecordId = getEntity().getHealthRecordId();
try {
latestHeight = (Height)em.createNamedQuery("Height.getLatestByHealthRecordId")
.setParameter("healthRecordId", healthRecordId)
.setMaxResults(1)
.getSingleResult();
}
catch (NoResultException ex) {
calculateBMI = false;
}
try {
latestWeight = (Weight)em.createNamedQuery("Weight.getLatestByHealthRecordId")
.setParameter("healthRecordId", healthRecordId)
.setMaxResults(1)
.getSingleResult();
}
catch (NoResultException ex) {
calculateBMI = false;
}
}
catch (Exception ex) {
calculateBMI = false;
} finally {
PersistenceService.getInstance().close();
}
double bmi = 0;
if (calculateBMI) {
int inches = 1; //avoid div by 0
double pounds = 0;
try {
inches = (latestHeight.getFeet() * 12) + latestHeight.getInches();
}
catch(Exception ex) {
inches = 1;
}
try {
if (latestWeight.getUnit().equalsIgnoreCase("lbs")) {
pounds = latestWeight.getWeight().intValue();
} else if (latestWeight.getUnit().equalsIgnoreCase("kgs")) {
//convert kgs to pounds
pounds = latestWeight.getWeight().doubleValue() * 2.20462262;
} else {
throw new Exception();
}
}
catch(Exception ex) {
pounds = 0;
}
if (inches>0 && pounds>0) {
//bmi formula http://www.whathealth.com/bmi/formula.html
bmi = pounds * 703;
bmi = bmi / (inches * inches);
}
}
try {
if (bmi>0) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
jSONObject.put("bmi", Double.valueOf(twoDForm.format(bmi)));
}
} catch (JSONException ex) {
logger.warn( "Error creating BMI JSONObject", ex);
}
try {
if (latestWeight != null) {
jSONObject.put("weight", latestWeight.getWeight().toString().concat(" ").concat(latestWeight.getUnit().toLowerCase()));
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
jSONObject.put("weightDate", df.format(latestWeight.getObservedDate()));
}
} catch (JSONException ex) {
logger.warn( "Error creating Weight JSONObject", ex);
}