/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package clips.delegate.doctor.checkup;
import beans.doctor.checkup.dicom.CheckupDicomBean;
import beans.doctor.checkup.dicom.CheckupDicomBeanRemote;
import cli_fmw.delegate.DelegateLine2;
import cli_fmw.delegate.cache.DelegateSecondaryCache;
import cli_fmw.delegate.cache.DelegateSecondaryCacheDgt;
import cli_fmw.delegate.cache.ExtraDataManager;
import cli_fmw.delegate.cache.SecondaryCacheManager;
import cli_fmw.delegate.lists.DataChunkList;
import clips.dicom.dicombaseclass.DICOMChekup;
import clips.dicom.dicombaseclass.DICOMDeviceParam;
import clips.dicom.dicombaseclass.DICOMException;
import clips.dicom.dicomdataimpl.DICOMDataDump;
import clips.dicom.dicomdataimpl.DicomFileInput;
import clips.dicom.model.Agregator;
import clips.dicom.model.AgregatorItem;
import clips.dicom.model.ItemEvent;
import clips.dicom.model.ItemListener;
import cli_fmw.main.ClipsException;
import cli_fmw.utils.MessageBox;
import cli_fmw.utils.SelectorEditable;
import beans.doctor.checkup.dicom.CheckupDicomDataDetails;
import beans.doctor.checkup.dicom.CheckupDicomDetails;
import cli_fmw.delegate.AuditListener;
import clips.doctor.newEMC.init.generic.DelegateNodeLeaf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import framework.utils.Converter;
import framework.utils.Pair;
/**
*
* @author finder
*/
public class CheckupDICOMLocal extends DelegateNodeLeaf<CheckupDicomBeanRemote, CheckupDicomDetails> implements ItemListener {
static final String DICOM_CHECKUP_XML_ITEM_NAME = "dicomitem";
static final String DICOM_CHECKUP_XML_ROOT_NAME = "dicom_instance_config";
DelegateSecondaryCache<CheckupLocal> checkup = new DelegateSecondaryCache<CheckupLocal>(getSCM(), "информацию об осмотре") {
@Override
protected void setPrimary(CheckupLocal type) throws ClipsException {
getDetails().checkupID = type.getID();
}
@Override
protected CheckupLocal init() throws Exception {
return null;
}
};
DataList data = new DataList(getEDM());
DelegateSecondaryCacheDgt<DicomDeviceParamsLocal> params =
new DelegateSecondaryCacheDgt<DicomDeviceParamsLocal>(getSCM(), false, "параметры устройства"){
@Override
protected void setPrimary(DicomDeviceParamsLocal type) throws ClipsException {
getDetails().deviceParamsID = type.getID();
}
@Override
protected DicomDeviceParamsLocal init() throws Exception {
return new DicomDeviceParamsLocal(getDetails().deviceParamsID, getAuditListener());
}
};
/*DelegateExtraCache<AgregatorItem> agregator = new DelegateExtraCache<AgregatorItem>(getECM()) {
@Override
protected void setPrimary(AgregatorItem type) throws ClipsException {
storeAgregator(type);
}
@Override
protected AgregatorItem init() throws Exception {
AgregatorItem target = loadAgregator();
target.addListener(CheckupDICOMLocal.this);
return target;
}
};*/
AgregatorItem agregator = null;
DelegateSecondaryCache<ArrayList<DICOMDataDump>> toDelete
= new DelegateSecondaryCache<ArrayList<DICOMDataDump>>(getSCM(), "данные объекта DICOM") {
@Override
protected void setPrimary(ArrayList<DICOMDataDump> type) throws ClipsException {
}
@Override
protected ArrayList<DICOMDataDump> init() throws Exception {
return new ArrayList<DICOMDataDump>();
}
};
CheckupDICOMLocal(CheckupDicomDetails d, CheckupLocal chl, AuditListener al) throws ClipsException {
super(d, al);
checkup.initBy(chl);
}
public CheckupDICOMLocal(CheckupLocal chl, AgregatorItem objects) throws ClipsException {
super(chl.getAuditListener());
checkup.initBy(chl);
agregator = objects;
setObjects(agregator);
storeAgregator(agregator);
objects.addListener(CheckupDICOMLocal.this);
}
@Override
protected CheckupDicomDetails getNewDetails() {
return new CheckupDicomDetails();
}
@Override
protected String getBeanName() {
return CheckupDicomBean.class.getSimpleName();
}
public CheckupLocal getCheckup() throws ClipsException {
return checkup.get();
}
public void setCheckup(CheckupLocal inCheckup) throws ClipsException {
checkup.set(inCheckup);
}
SelectorEditable<CheckupDICOMLocalData> getData() throws ClipsException{
return data.selector();
}
void loadParamsFromXML(Element el, ArrayList<DICOMChekup> chekupList){
@SuppressWarnings("unchecked")
List<Element> list = el.getChildren(DICOM_CHECKUP_XML_ITEM_NAME);
if (chekupList.size() != list.size()){
return;
}
for (int i = 0; i < chekupList.size(); i++) {
DICOMChekup chekup = chekupList.get(i);
chekup.loadConfigFromXML(list.get(i));
}
}
private AgregatorItem loadAgregator() throws ClipsException, IOException, DICOMException{
SelectorEditable<CheckupDICOMLocalData> dataList = getData();
TreeMap<Integer, ArrayList<DICOMChekup>> target = new TreeMap<Integer, ArrayList<DICOMChekup>>();
DicomFileInput fi = new DicomFileInput();
for (int i = 0; i < dataList.size(); i++) {
CheckupDICOMLocalData object = dataList.get(i);
ArrayList<DICOMChekup> cur = fi.decodeZipFile(object.getValue(), false);
DICOMDataDump dump = new DICOMDataDump(object.getValue(), true);
for (DICOMChekup chekup : cur) {
chekup.setOriginalData(dump);
}
try {
loadParamsFromXML(Converter.stringToXml(object.getXml()).getRootElement(), cur);
} catch (JDOMException ex) {
ex.printStackTrace();
}
target.put(object.getCheckupOrder(), cur);
}
ArrayList<DICOMChekup> summ = new ArrayList<DICOMChekup>();
for (ArrayList<DICOMChekup> object : target.values()) {
summ.addAll(object);
}
if (summ.size() > 0){
AgregatorItem item = new AgregatorItem(summ, AgregatorItem.ItemsType.indefine(summ.get(0)));
return item;
}
else {
throw new ClipsException("Отсутствуют DICOM объекты в базе данных");
}
}
private void storeParam(DICOMDeviceParam prarm) throws ClipsException{
DicomDeviceParamsLocal search = new DicomDeviceParamsSearchLocal(getAuditListener()).findDevice(prarm);
if (prarm.getDeviceID() == 0){
if (search != null) {
setParams(search);
return;
}
search = new DicomDeviceParamsLocal(getAuditListener());
}
else{
if (search.getID() != prarm.getDeviceID()) {
setParams(search);
return;
}
}
search.setFrom(prarm);
if (search.isDirty()) {
search.save1();
}
setParams(search);
}
private void storeAgregator(AgregatorItem items) throws ClipsException{
ArrayList<DICOMChekup> list = items.getItems();
if (list.size() == 0){
throw new ClipsException("Попытка сохранить пустой список объектов");
}
DICOMDeviceParam prarm = list.get(0).getDeviceParam();
if (prarm != null) {
storeParam(prarm);
}
ArrayList<Pair<DICOMDataDump, Element>> target = new ArrayList<Pair<DICOMDataDump, Element>>();
for (int i = 0; i < list.size(); i++) {
DICOMChekup chekup = list.get(i);
Pair<DICOMDataDump, Element> cur = null;
for (Pair<DICOMDataDump, Element> pair : target) {
if (pair.first == chekup.getOriginalData()){
cur = pair;
}
}
if (cur == null){
cur = new Pair<DICOMDataDump, Element>();
cur.first = chekup.getOriginalData();
cur.second = new Element(DICOM_CHECKUP_XML_ROOT_NAME);
target.add(cur);
}
Element save = chekup.saveConfigToXML(DICOM_CHECKUP_XML_ITEM_NAME);
cur.second.addContent(save);
}
SelectorEditable<CheckupDICOMLocalData> sel = data.selector();
ArrayList<DICOMDataDump> deleteList = new ArrayList<DICOMDataDump>();
int i = 0;
while (i < target.size()) {
Pair<DICOMDataDump, Element> pair = target.get(i);
CheckupDICOMLocalData dataItem;
if (sel.size() > i) {
dataItem = sel.get(i);
}
else {
dataItem = new CheckupDICOMLocalData(new CheckupDicomDataDetails());
sel.append(dataItem);
}
try{
dataItem.setValue(pair.first.getDumpData());
deleteList.add(pair.first);
}
catch (IOException ex){
ex.printStackTrace();
}
dataItem.setXml(Converter.xmlToString(new Document(pair.second)));
dataItem.setCheckupOrder(i);
i++;
}
toDelete.set(deleteList);
while (i < sel.size()){
sel.remove(sel.size() - 1);
}
}
public DicomDeviceParamsLocal getParams() throws ClipsException{
return params.get();
}
public void setParams(DicomDeviceParamsLocal inparams) throws ClipsException{
params.set(inparams);
}
public AgregatorItem getObjects() throws ClipsException{
if (agregator == null) {
try {
setObjects(loadAgregator());
} catch (IOException ex){
throw new ClipsException("Ошибка при загрузке", ex);
} catch (DICOMException ex) {
throw new ClipsException("Ошибка при загрузке", ex);
}
}
return agregator;
}
private void setObjects(AgregatorItem objects) throws ClipsException {
agregator = objects;
agregator.addListener(CheckupDICOMLocal.this);
}
@Override
public void save1() throws ClipsException {
if (agregator != null){
storeAgregator(agregator);
super.save1();
for (DICOMDataDump dataDump : toDelete.get()) {
try {
dataDump.delete();
} catch (IOException ex) {
toDelete.set(new ArrayList<DICOMDataDump>());
throw new ClipsException("Не удалось удалить фаил дампа", ex);
}
}
toDelete.set(new ArrayList<DICOMDataDump>());
}
}
@Override
public void afterRemove() {
super.afterRemove();
if (agregator != null){
agregator.removeListener(this);
Agregator.saveItemOrFinallyRemove(agregator);
}
}
@Override
public void restore() {
if (isNewlyCreated()){
Agregator.addItem(agregator);
afterRemove();
}
else{
if (agregator != null){
agregator.removeListener(this);
agregator = null;
}
}
super.restore();
}
class DataList extends DataChunkList<CheckupDICOMLocalData>{
public DataList(ExtraDataManager contaner) {
super(contaner);
}
@Override
protected void deleteDB(CheckupDICOMLocalData data) throws Exception {
getBean().removeData(data.getId());
}
@Override
protected int saveDB(CheckupDICOMLocalData data) throws Exception {
return getBean().setData(data.getDetails());
}
@Override
protected void loadDB() throws Exception {
for (CheckupDicomDataDetails detal : getBean().getData()) {
initByDetails(new CheckupDICOMLocalData(detal));
}
}
}
@Override
public String toString() {
try {
if (getParams() != null) {
return getParams().toString();
}
else {
return "<Ошибка>";
}
} catch (ClipsException ex) {
ex.printStackTrace();
return "<Ошибка>";
}
}
@Override
public void itemStateChanged(ItemEvent e) {
try {
storeAgregator(agregator);
fireContentStateEvent();
} catch (ClipsException ex) {
ex.printStackTrace();
}
}
}