/**
*
*/
package org.mbhcare.server;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import org.datanucleus.query.evaluator.memory.DateAggregateExpression;
import org.mbhcare.client.rpc.DiagnosisService;
import org.mbhcare.shared.FieldVerifier;
import org.mbhcare.shared.entity.Diagnosis;
import org.mbhcare.shared.entity.EntityDisplay;
import org.mbhcare.shared.entity.Fetal;
import org.mbhcare.shared.entity.Patient;
import org.mbhcare.shared.exception.ServerException;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.repackaged.com.google.common.collect.Lists;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
/**
* @author Tuan Truong
*
*/
@SuppressWarnings("serial")
public class DiagnosisServiceImpl extends RemoteServiceServlet
implements DiagnosisService {
private static final Logger log =
Logger.getLogger(DiagnosisServiceImpl.class.getName());
@SuppressWarnings("unchecked")
@Override
public List<EntityDisplay> selectByFields(List<String> fields, List<String> values) throws ServerException {
PersistenceManager pm = PMF.get().getPersistenceManager();
List<EntityDisplay> result;
if (!LoginServiceImpl.isLoggedIn()) {
throw new IllegalArgumentException("User not loggin error.");
} else {
try {
String criterias = "userAccount == param_userAccount";
String declareParams = "String param_userAccount";
Date dateStartNk = null;
Date dateEndNk = null;
Number diagtype = 0;
Calendar c = Calendar.getInstance();
int count = 1;
for(int i = 0; i< fields.size(); i++) {
String field = fields.get(i);
String value = values.get(i);
if (!value.equals("") && field.equals("ngaykham_start")) {
// dateStartNk = new Date(0);
// dateStartNk.setTime(Long.valueOf(value));
// dateEndNk = new Date(0);
// dateEndNk.setTime(Long.valueOf(value));
// //c.setTimeZone(TimeZone.getTimeZone("GMT+7"));
// c.setTime(dateStartNk);
// c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), 0, 1, 1);
// dateStartNk = c.getTime();
// c.setTime(dateEndNk);
// c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), 23 , 59, 59);
// dateEndNk = c.getTime();
// criterias += " && ngaykham >= param_ngaykham && ngaykham <= param_ngaykham2";
dateStartNk = new Date(0);
dateStartNk.setTime(Long.valueOf(value));
criterias += " && ngaykham >= ngaykham_start";
declareParams += ", java.util.Date ngaykham_start";
count++;
} else if (!value.equals("") && field.equals("ngaykham_end")) {
dateEndNk = new Date(0);
dateEndNk.setTime(Long.valueOf(value));
criterias += " && ngaykham <= ngaykham_end";
declareParams += ", java.util.Date ngaykham_end";
count++;
} else if (!value.equals("") && field.equals("diagnostictype")) {
diagtype = Integer.valueOf(value);
criterias += " && diagnostictype == diagtype";
declareParams += ", Number diagtype";
count++;
}
}
Query query = pm.newQuery(Diagnosis.class);
query.declareParameters(declareParams);
String filter = criterias;
query.setFilter(filter);
query.setOrdering("ngaykham desc");
Object[] objs = new Object[count];
objs[0] = LoginServiceImpl.getAcccout();
if (count == 4) {
objs[1] = dateStartNk;
objs[2] = dateEndNk;
objs[3] = diagtype;
//Object[] objs = new Object[]{LoginServiceImpl.getAcccout()
// , dateStartNk, dateEndNk, diagtype};
} else if (count == 3) {
objs[1] = dateStartNk;
objs[2] = dateEndNk;
} else {
List<Diagnosis> diagnosis = (List<Diagnosis>)query.executeWithArray(
LoginServiceImpl.getAcccout());
result = parseEntityDisplay(diagnosis);
}
List<Diagnosis> diagnosis = (List<Diagnosis>)query.executeWithArray(objs);
result = parseEntityDisplay(diagnosis);
} catch(Exception e) {
throw new ServerException(e.toString());
} finally {
pm.close();
}
}
return result;
}
@Override
public void delete(List<String> ids) throws ServerException {
PersistenceManager pm = PMF.get().getPersistenceManager();
String result = "";
try {
//pm.currentTransaction().begin();
for(String id : ids) {
Query query = pm.newQuery(DiagnosisImage.class);
query.setFilter("diagnosis == :diagnosis");
List<DiagnosisImage> existences = (List<DiagnosisImage>)query.execute(id);
//delete related image
for (DiagnosisImage item : existences){
pm.deletePersistent(item);
}
//delete diagnosisitem
Diagnosis diagnosis = pm.getObjectById(Diagnosis.class, id);
pm.deletePersistent(diagnosis);
}
//pm.currentTransaction().commit();
} catch(Exception e) {
pm.currentTransaction().rollback();
result = result + e.toString();
}
if(!result.isEmpty()) {
throw new ServerException(result);
}
}
@Override
public Diagnosis selectById(String id) throws ServerException {
PersistenceManager pm = PMF.get().getPersistenceManager();
Diagnosis diagnosis;
try {
diagnosis = pm.getObjectById(Diagnosis.class, id);
} catch(Exception e) {
throw new ServerException(e.toString());
}
return diagnosis;
}
@SuppressWarnings("unchecked")
@Override
public List<EntityDisplay> selectByPatient(String id) throws ServerException {
PersistenceManager pm = PMF.get().getPersistenceManager();
List<EntityDisplay> result;
try {
Query query = pm.newQuery(Diagnosis.class);
query.setFilter("patient == :patient");
query.setOrdering("ngaykham desc");
List<Diagnosis> diagnosis = (List<Diagnosis>)query.execute(id);
result = parseEntityDisplay(diagnosis);
} catch(Exception e) {
throw new ServerException(e.toString());
} finally {
pm.close();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
public List<EntityDisplay> selectNineMonths(String patient, String fetal) throws ServerException {
PersistenceManager pm = PMF.get().getPersistenceManager();
List<Diagnosis> diagnosis;
List<EntityDisplay> result = null;
try {
Query query = pm.newQuery(Diagnosis.class);
//query.setFilter("ngaykham >= :ngaykham");
query.setFilter("patient == :patient && fetal == :fetal");
//query.setOrdering("ngaykham desc");
diagnosis = (List<Diagnosis>)query.execute(patient,fetal);
result = parseEntityForReport(diagnosis);
} catch(Exception e) {
throw new ServerException(e.toString());
} finally {
pm.close();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
public List<Diagnosis> select(String filter) throws ServerException {
PersistenceManager pm = PMF.get().getPersistenceManager();
List<Diagnosis> result;
try {
Query query = pm.newQuery(Patient.class);
query.setFilter(filter);
query.setOrdering("firstname asc");
result = (List<Diagnosis>) query.execute();
result = Lists.newArrayList(pm.detachCopyAll(result));
} catch(Exception e) {
throw new ServerException(e.toString());
} finally {
pm.close();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
public List<EntityDisplay> selectDisplay() throws ServerException {
PersistenceManager pm = PMF.get().getPersistenceManager();
List<EntityDisplay> result;
try {
Query query = pm.newQuery(Diagnosis.class);
query.setOrdering("ngaykham desc");
if (!LoginServiceImpl.isLoggedIn()) {
throw new IllegalArgumentException("User not loggin error.");
} else {
query.setFilter("userAccount == :userAccount");
List<Diagnosis> diagnosis = (List<Diagnosis>) query.execute(LoginServiceImpl.getAcccout());
// for(Diagnosis item: diagnosis) {
//
// String ngaykham = "";
// if (item.getNgaykham() != null)
// {
// ngaykham = Long.toString(item.getNgaykham().getTime());
// }
// result.add(new EntityDisplay(new String[] {
// patient.getId(), patient.getFirstName(),
// patient.getLastName(), birthday,
// patient.getAddress(),patient.getPhone(),
// patient.getEmail(),patient.getNotes()}));
// }
result = parseEntityDisplay(diagnosis);
}
} catch(Exception e) {
throw new ServerException(e.toString());
} finally {
pm.close();
}
return result;
}
private List<EntityDisplay> parseEntityDisplay(List<Diagnosis> diagnosis) {
ArrayList<EntityDisplay> result = new ArrayList<EntityDisplay>();
for(Diagnosis item: diagnosis) {
String ngaykham = "";
if (item.getNgaykham() != null)
{
ngaykham = Long.toString(item.getNgaykham().getTime());
}
String type = "0";
if (item.getDiagnostictype() != null)
{
type = item.getDiagnostictype().toString();
}
result.add(new EntityDisplay(new String[] {
item.getId(),
ngaykham, type,
item.getKetluanchung().getDescription()
}));
}
return result;
}
private List<EntityDisplay> parseEntityForReport(List<Diagnosis> diagnosis) {
ArrayList<EntityDisplay> result = new ArrayList<EntityDisplay>();
for(Diagnosis item: diagnosis) {
String ngaykham = "";
if (item.getNgaykham() != null)
{
ngaykham = Long.toString(item.getNgaykham().getTime());
}
result.add(new EntityDisplay(new String[] {
ngaykham,
item.getChieudaixuongdui().toString(),
item.getChieudaidaumong().toString(),
item.getChuvivongdau().toString(),
item.getChuvibung().toString(),
item.getDuongkinhluongdinh().toString()
}));
}
return result;
}
private void ClearAll() throws ServerException{
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query1 = pm.newQuery(Diagnosis.class);
List<Diagnosis> diagnosis1 = (List<Diagnosis>) query1.execute();
try {
pm.deletePersistentAll(diagnosis1);
} catch(Exception e) {
throw new ServerException(e.toString());
} finally {
pm.close();
}
}
@Override
public Diagnosis save(Diagnosis diagnosis) throws ServerException {
// Verify that the input is valid.
if(!FieldVerifier.isValidString(diagnosis.getPatient()) &&
!FieldVerifier.isValidString(diagnosis.getPatient())) {
throw new IllegalArgumentException("FieldVerifier error.");
}
if (!LoginServiceImpl.isLoggedIn()) {
throw new IllegalArgumentException("User not loggin error.");
} else {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.currentTransaction().begin();
//if new then add
if (diagnosis.getFetal() == null || diagnosis.getFetal().equals("")){
//get last time
Query query = pm.newQuery(Fetal.class);
query.setFilter("patient == :patient");
query.setResult("count(this)");
int count = (Integer)query.execute(diagnosis.getPatient());
//insert new one
Fetal newfetal = new Fetal();
newfetal.setNgaykinhcuoi(diagnosis.getNgaykinhcuoi());
newfetal.setPatient(diagnosis.getPatient());
//newfetal.setDisplayType(diagnosis.getFetalDisplayType());
newfetal.setTime(count+1);
pm.makePersistent(newfetal);
//set new fetal for diagnosis
diagnosis.setFetal(newfetal.getId());
//else update ngaykinhcuoi
} else {
Fetal fetal = pm.getObjectById(Fetal.class, diagnosis.getFetal());
fetal.setNgaykinhcuoi(diagnosis.getNgaykinhcuoi());
pm.makePersistent(fetal);
}
pm.currentTransaction().commit();
// Is a insert statement?
if(diagnosis.getId() == null) {
Query query = pm.newQuery(Diagnosis.class);
query.setResult("count(this)");
}
//try {
//pm.currentTransaction().begin();
// TODO check this
if(diagnosis.getId() != null) {
Diagnosis temp = pm.getObjectById(Diagnosis.class, diagnosis.getId());
//temp.getFlags();
}
diagnosis.setUserAccount(LoginServiceImpl.getAcccout());
pm.currentTransaction().begin();
pm.makePersistent(diagnosis);
pm.currentTransaction().commit();
} catch(Exception e) {
pm.currentTransaction().rollback();
throw new ServerException(e.toString());
} finally {
pm.close();
}
}
return diagnosis;
}
public void deleteImage(List<String> ids) throws ServerException {
if (!LoginServiceImpl.isLoggedIn()) {
throw new IllegalArgumentException("User not loggin error.");
} else {
PersistenceManager pm = PMF.get().getPersistenceManager();
String result = "";
try {
for(String id : ids) {
//delete image
DiagnosisImage image = pm.getObjectById(DiagnosisImage.class, id);
pm.deletePersistent(image);
}
} catch(Exception e) {
result = result + e.toString();
}
if(!result.isEmpty()) {
throw new ServerException(result);
}
}
}
@SuppressWarnings("unchecked")
public List<EntityDisplay> selectDisplayImageByDiagnosis(String id) throws ServerException {
ArrayList<EntityDisplay> result = new ArrayList<EntityDisplay>();
if (!LoginServiceImpl.isLoggedIn()) {
throw new IllegalArgumentException("User not loggin error.");
} else {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(DiagnosisImage.class);
query.setFilter("diagnosis == :diagnosis");
query.setOrdering("createdAt desc");
List<DiagnosisImage> diagnosisImage = (List<DiagnosisImage>)query.execute(id);
for (DiagnosisImage item : diagnosisImage) {
result.add(new EntityDisplay(new String[] {
item.getId()}));
}
}
return result;
}
public void saveImage(String diagnosisId, List<String> keys) throws ServerException {
if (!LoginServiceImpl.isLoggedIn()) {
throw new IllegalArgumentException("User not loggin error.");
} else {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
//pm.currentTransaction().begin();
for (String key : keys) {
DiagnosisImage image = pm.getObjectById(DiagnosisImage.class, key);
log.info("image key :" + key);
image.setDiagnosis(diagnosisId);
pm.makePersistent(image);
}
//pm.currentTransaction().commit();
} catch(Exception e) {
//pm.currentTransaction().rollback();
throw new ServerException(e.toString());
} finally {
pm.close();
}
}
}
}