/*****************************************************************************
 *                                                                           *
 *  Copyright (c) 2010 by SANTEC/TUDOR www.santec.tudor.lu                   *
 *                                                                           *
 *                                                                           *
 *  This library is free software; you can redistribute it and/or modify it  *
 *  under the terms of the GNU Lesser General Public License as published    *
 *  by the Free Software Foundation; either version 2 of the License, or     *
 *  (at your option) any later version.                                      *
 *                                                                           *
 *  This software is distributed in the hope that it will be useful, but     *
 *  WITHOUT ANY WARRANTY; without even the implied warranty of               *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        *
 *  Lesser General Public License for more details.                          *
 *                                                                           *
 *  You should have received a copy of the GNU Lesser General Public         *
 *  License along with this library; if not, write to the Free Software      *
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA  *
 *                                                                           *
 *****************************************************************************/
package lu.tudor.santec.gecamed.usermanagement.gui;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.UIManager;

import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialog;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntryType;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.IncidentManagerBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IncidentManager;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.Prescription;
import lu.tudor.santec.gecamed.prescription.ejb.session.beans.PrescriptionManagerBean;
import lu.tudor.santec.gecamed.prescription.ejb.session.interfaces.PrescriptionManager;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Logger;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;


/** 
 * Dialog where user can create incidents entries for prescriptions how have only one incident entries together.
 * To open the dialog navigate in main menu to Admin.
 * 
 * @author Thorsten Roth thorsten.roth(at)tudor.lu
 *
 * @version
 * <br>$Log: DataBaseDialogCreatePrescriptionIncidentsEntries.java,v $
 * <br>Revision 1.8  2013-12-27 18:09:25  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.7  2013-07-15 06:18:36  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.6  2012-01-18 09:19:41  ferring
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.5  2011-03-21 14:18:56  troth
 * <br>Add one step to the database clear up script which try to fix incident entries where the incident id is null (over the incident id of there childs).
 * <br>
 * <br>Revision 1.4  2010-11-04 13:34:30  troth
 * <br>update of the function that "create Incident Entries for Prescription how have one together" now in the second step the Select select only the needed Prescriptions thats much more faster.
 * <br>
 * <br>Revision 1.3  2010-11-03 17:45:06  troth
 * <br>expansion of the function that "create Incident Entries for Prescription how have one together" now it also
 * <br>1. sync the incidentIds of Prescriptions and there Incident Entry
 * <br>2. deletes Incidents how have no Incident Entries and no back link from a Prescription
 * <br>
 * <br>Revision 1.2  2010-10-18 07:47:54  troth
 * <br>add translations - for the function create Incidententries for Prescription how have one together
 * <br>
 * <br>Revision 1.1  2010-10-15 14:57:42  troth
 * <br>add function to create Incidententries for Prescription how have one together
 * <br>
 */
public class DataBaseDialogCreatePrescriptionIncidentsEntries extends GECAMedBaseDialog{
	
	private static final 	long 				serialVersionUID 	= 1L;

	private static final 	Color 				SPLASH_TEXTCOLOR 	= new Color(0,67,134);
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(DataBaseDialogCreatePrescriptionIncidentsEntries.class.getName());
	
	private 				CellConstraints 	cc;
	
	private 				JProgressBar 		progressBar;
	
	private 				JButton 			startButton;
	
	private 				JButton 			stopButton;
	
	private 				JTextArea 			textArea;
	
	private 				JPanel 				parentPanel;
	
	private 				Thread 				thread;
	
	private 				Boolean 			stop;

	private 				int 				incidentEntryIdsSize;
	
	private 				List<Integer> 		incidentEntryIds;
	
	private 				IncidentManager 	incidentManager;
	
	private 				PrescriptionManager prescriptionManager;
	
	private 				long 				runTime;
	
	private 				String 				infoText;
	
	
	/**
	 * Constructor
	 * 
	 * @param title of dialog
	 */
	public DataBaseDialogCreatePrescriptionIncidentsEntries(String title) {
		super(title,true,false);
		
		this.prescriptionManager = (PrescriptionManager) ManagerFactory.getRemote(PrescriptionManagerBean.class);
		this.incidentManager = (IncidentManager) ManagerFactory.getRemote(IncidentManagerBean.class);
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		
		this.initValues();
		this.initComponents();
		this.buildPanel();
		
		this.pack();
	}


	/**
	 * init all values
	 */
	private void initValues() {
		this.stop = false;
		// get all incidentEntries where the incident id is null
		incidentEntryIds = incidentManager.getIncidentEntriesIdWhereIncidentIdIsNull();
		incidentEntryIdsSize = incidentEntryIds.size(); 
		// set info text
		if(incidentEntryIdsSize > 0) infoText = Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.infoTextStepOne");
		else infoText = Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.infoTextStepOneDone");
	}

	
	/**
	 * build the dialog gui 
	 */
	private void buildPanel()
	{
		this.parentPanel = new JPanel(
				new FormLayout(
						// cols
						"3dlu," +
						"fill:pref:grow," +
						"25dlu," +
						"fill:pref:grow," +
						"3dlu",
						// rows
						"3dlu," +
						"fill:200dlu," + // info text
						"3dlu," +
						"fill:25dlu," + // progressBar
						"3dlu," +
						"fill:20dlu," + // buttons
						"3dlu"));
		this.parentPanel.setBackground(GECAMedColors.c_GECAMedBackground);
		this.parentPanel.setOpaque(false);
		
		this.cc = new CellConstraints();
		
		
		
//		if(this.IncidentEntryIds.size() > 0)
//		{
			this.parentPanel.add(new JScrollPane(this.textArea), 	cc.xyw(2, 2, 3));
			this.parentPanel.add(this.progressBar,					cc.xyw(2, 4, 3));
			this.parentPanel.add(this.startButton,					cc.xyw(2, 6, 1));
			this.parentPanel.add(this.stopButton,					cc.xyw(4, 6, 1));
//		}else
//			this.parentPanel.add(new JScrollPane(this.textArea),	cc.xywh(2, 2, 3, 5));
		
		this.add(parentPanel);
	}
	
	/**
	 * init dialog components.
	 * The action of the ok button starts the clearing/correcting incident tree script.
	 */
	private void initComponents()
	{
		// init info text
		this.textArea = new JTextArea();
		this.textArea.setFont(new Font(null, Font.BOLD, 14));
		this.textArea.setEditable(false);
		this.textArea.setLineWrap(true);
        this.textArea.setWrapStyleWord(true);
		this.textArea.setAutoscrolls(true);
		this.textArea.setSize(400, 400);
		textArea.setText(infoText);
		
		// init progressBar
		this.progressBar = new JProgressBar(SwingConstants.HORIZONTAL, 0, incidentEntryIdsSize);
		UIManager.put("ProgressBar.selectionBackground",SPLASH_TEXTCOLOR);
        this.progressBar.setStringPainted(true);
        this.progressBar.setBackground(Color.WHITE);
        this.progressBar.setForeground(SPLASH_TEXTCOLOR);
        this.progressBar.setString("0 / " + incidentEntryIdsSize + " | step 1/4");
        
        // init buttons
		this.startButton = new JButton(Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.startButton"));
		this.startButton.setEnabled(true);
		this.startButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				startButton.setEnabled(false);
				stopButton.setEnabled(true);
				okButton.setEnabled(false);
				
				stop = false;
				
				//initValues();
				//stop = false;
				runTime = System.currentTimeMillis();
				thread = new Thread(new Runnable() {

					public void run()
					{
						logger.info("Start Incident/IncidentEntry clearing script.");
						int lastStepListSize = 0;
						int lastStepCurrentItem = 0;
						int lastStep = 0;
						String lastStepInfoText = "";
						int i = 0;
						int numberOfSteps = 4;
						////////////////////////////////////////////////////////////////////////
						// Step 1 of 4
						// look if incident id of incidents entries are set.
						// if not take the incident of there child entry.
						// if the incident entry has no child entry create a new incident if possible else delete incident entry
						lastStep = 1 ;
						// get all incident entry where incident id is null
						incidentEntryIds = incidentManager.getIncidentEntriesIdWhereIncidentIdIsNull();
						incidentEntryIdsSize = incidentEntryIds.size();
						logger.info("Step " + lastStep + "/" + numberOfSteps + ": Look for IncidentEnrty where incident id is null. Select " + incidentEntryIdsSize + " IncidentEntry.");
						// set info text
						if(incidentEntryIdsSize > 0) infoText = Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.infoTextStepOne");
						else infoText = Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.infoTextStepOneDone");
						textArea.setText(infoText);
						// init progress Bar
						progressBar.setMaximum(incidentEntryIdsSize);
						// some counters for step 1
						int countIEwP = 0;
						int countIEwoP = 0;
						int countIEnI = 0;
						
						for ( Integer incidentEntryId : incidentEntryIds)
						{
							// break FOR if stopButton is press
							if(stop)
							{
								//lastStep = 1 ;
								lastStepListSize = incidentEntryIdsSize;
								lastStepCurrentItem = i;
								lastStepInfoText = infoText;	
								break;
							}
							// update progress bar
							progressBar.setValue(i);
							progressBar.setString(i + " / " + incidentEntryIdsSize + " | " + Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.step") + " " + lastStep + "/" + numberOfSteps);
							
							Boolean haveIncidentIdFromChild = false;
							// get incident entry by id
							IncidentEntry incidentEntry = incidentManager.getIncidentEntry(incidentEntryId);
							
							// incident Id of incident entry is null try to get the incident Id over the child of incident entry 
							if(incidentEntry.getIncidentId() == null) //&& prescription.getIncidentId() == null)
							{
								try {
									// get child (in our case we have only to look at prescription childs until now)
									if((incidentEntry.getEntryType().getName()).equals(IncidentManager.PRESCRIPTION))
									{
										List<Prescription> prescriptions = prescriptionManager.getPrescriptionByIncidentEntry(incidentEntry.getId());
										if(prescriptions.size() != 0)
										{
											// may be there are more than one prescription so we take the first 
											Prescription prescription = prescriptions.get(0);
											Incident incident = incidentManager.getIncident(prescription.getIncidentId());
											incidentEntry.setIncident(incident);
											incidentEntry.setIncidentId(prescription.getIncidentId());
											incidentEntry = incidentManager.saveEntry(incidentEntry, IncidentManager.PRESCRIPTION);
											prescription.setIncidentEntry(incidentEntry);
											haveIncidentIdFromChild = true;
											countIEwP++;
										}else{
											countIEwoP++;
											haveIncidentIdFromChild = true;
											// in this case the incident entry is form type prescription but it have no prescription and
											// no incident id so it can be deleted
											Integer iEiD = incidentEntry.getId();
											incidentEntry = null;
											incidentManager.deleteIncidentEntry(iEiD);
											logger.info("IncidentEntry " + iEiD + " type is Prescription but IncidentEntry has no Prescription. Deleted IncidentEnrty " + iEiD);
											
										}
									}else{
										logger.warn("Incident id of IndcidentEntry " + incidentEntry.getId() + " is null. The Type of IncidentEntry is " + incidentEntry.getEntryType().getName());		
									}
									// if in future you want to check other childs if they had a incident id place it here.
								}catch (Exception ex){
									logger.warn("Error: IncidentEntry have no Type. IncidentEntry  id: " + incidentEntry.getId() + ". Exception: " + ex);
								}
								
								// if the incident entry have not get a incident id form a child
								if(!haveIncidentIdFromChild)
								{
									countIEnI++;
								}
							}
							// why set the thread sleeping ? out
//							try
//							{
//								Thread.sleep(10);
//							} catch (Exception ex) {
//							}
							i++;
						}
						logger.info("selected IncidentEntry: " + incidentEntryIdsSize + " | IE get id form child: " + countIEwP + " | IE-P deleted: " + countIEwoP + " | exist null IE: " + countIEnI);
						////////////////////////////////////////////////////////////////////////
						// Step 2 of 4
						// Create new incident entry for prescriptions how have no
						lastStep = 2;
						logger.info("Step " + lastStep + "/" + numberOfSteps + ": Create new incident entry for prescriptions how have no");
						i = 0;
						// get IncidentEntryType of prescription 
						IncidentEntryType incidentEntryType = incidentManager.getTypeByName(IncidentManager.PRESCRIPTION,"text/plain");
						
						// some counters for Step 2
						int countIEright = 0;
						int countIESync = 0;
						int countIECreate = 0;
						
						// get all incidentEntries witch have more than one prescription
						List<Integer> incidentEntryIdList = incidentManager.getIncidentEntriesIdWithPrescriptions();
						
						int incidentEntryIdListSize = incidentEntryIdList.size(); 
						// set info text
						if(incidentEntryIdListSize > 0) infoText = Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.infoTextStepTwo");
						else infoText = Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.infoTextStepTwoDone");
						
						textArea.setText(infoText);
						progressBar.setMaximum(incidentEntryIdListSize);
						
						logger.info(incidentEntryIdList.size() + " incidentEntries have more than one prescription ...");
						// run over all incidentEntries witch have more than one prescription
						for (Integer incidentEntryId : incidentEntryIdList)
						{
							// break FOR if stopButton is press
							if(stop)
							{
								//if(lastStep == 0) lastStep = 2;
								if(lastStepListSize == 0) lastStepListSize = incidentEntryIdListSize;
								if(lastStepCurrentItem == 0) lastStepCurrentItem = i;
								if(lastStepInfoText.equals("")) lastStepInfoText = infoText;
								//lastStep = 1;
								//lastStepListSize = incidentEntryIdsListSize;
								//lastStepCurrentItem = i;
								//lastStepInfoText = infoText;
								break;
							}
							// set progress on progressBar
							progressBar.setValue(i);
							progressBar.setString(i + " / " + incidentEntryIdListSize + " | " + Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.step") + " " + lastStep + "/" + numberOfSteps);
							
							// get IncidentEntry by id
							IncidentEntry incidentEntry = incidentManager.getIncidentEntry(incidentEntryId);
							// get all prescriptions of the incidentEntry
							List<Prescription> prescriptionList = incidentManager.getAllPrescriptionsOfIncidentEntry(incidentEntryId);
							//countPrescription = countPrescription + prescriptionList.size();
							
							// we have to generated a new IncidentEntry for each prescription with the exception of the first prescription
							int removeCount = 0;
							boolean removeItem = false;
							// find Prescription to remove if there is no, sync one with Entry and incident
							// find Prescription where IncidentId == IncidentId of IncidentEntry 
							for (Prescription prescription : prescriptionList)
							{
								
								//System.out.println("EI: "+ i +"|"+ c +"/"+ prescriptionListsize +" -> incidentEntry/IncidentId: "+ incidentEntry.getIncidentId() +"| prescription/IncidentId: "+ prescription.getIncidentId());
								
								
								if(incidentEntry.getIncidentId().equals(prescription.getIncidentId())){
									
									//System.out.println("Remove Prescription : " + removeCount + " --> incidentEntry/IncidentId: "+ incidentEntry.getIncidentId() +"| prescription/IncidentId: "+ prescription.getIncidentId());
									removeItem = true;
									prescriptionList.remove(removeCount);
									countIEright++;
									break;
									
								}
								removeCount++;
							}
							
//							int c = 0;
							boolean onetime = false;
							
							// run over all prescriptions
							for (Prescription prescription : prescriptionList)
							{
								//System.out.println(" -> incidentEntry/IncidentId: "+ incidentEntry.getIncidentId() +"| prescription/IncidentId: "+ prescription.getIncidentId());
								// sync the first prescription of prescription list because no one with the same IncidentId have found before.
								if(!removeItem && !onetime){
									onetime = true;
									
									//System.out.println("No Prescription so take the old Incident Entry");
									// set the data of the IncidentEntry
									Incident incident = incidentManager.getIncident(prescription.getIncidentId());
									incidentEntry.setIncident(incident);
									incidentEntry.setIncidentId(prescription.getIncidentId());
									
									incidentEntry.setEntryTypeId(incidentEntryType.getId());
									incidentEntry.setEntryType(incidentEntryType);
									incidentEntry.setCreated(prescription.getCreationDate());
									incidentEntry.setCreatedBy(prescription.getCreatedBy());
									incidentEntry.setModified(prescription.getCreationDate());
//									incidentEntry.setModifiedBy(prescription.getPhysicianId());
									incidentEntry.setModifiedBy(prescription.getCreatedBy());
									incidentEntry.setEntryDate(prescription.getCreationDate());
									// save new IncidentEntry to data base
									incidentEntry = incidentManager.saveEntry(incidentEntry, IncidentManager.PRESCRIPTION);
									// set the new IncidentEntry to the prescription
									prescription.setIncidentEntry(incidentEntry);
									prescription.setIncidentEntryId(incidentEntry.getId());
									// save the prescription to data base
									prescriptionManager.savePrescription(prescription);
									
//									System.out.println("No Prescription so take the old Incident Entry");
//									System.out.println("incidentEntry IncidentId: " + incidentEntry.getIncidentId());
//									System.out.println("incidentEntry Id: " + incidentEntry.getId());
//									System.out.println("prescription IncidentId: " + prescription.getIncidentId());
//									System.out.println("prescription incidentEntryId: " + prescription.getIncidentEntryId());
//									System.out.println("incidentEntry/IncidentId == prescription/IncidentId :" + countElse);
									countIESync++;
									
								} // else this are the prescriptions how have not there own incident entry
								else {
									//System.out.println("New Incident Entry");
									// generated for each prescription a new IncidentEntry
									IncidentEntry newIncidentEntry = new IncidentEntry();
									// set the data of the new IncidentEntry
									Incident incident = incidentManager.getIncident(prescription.getIncidentId());
									newIncidentEntry.setIncident(incident);
									newIncidentEntry.setIncidentId(prescription.getIncidentId());
									
									newIncidentEntry.setEntryTypeId(incidentEntryType.getId());
									newIncidentEntry.setEntryType(incidentEntryType);
									newIncidentEntry.setCreated(prescription.getCreationDate());
									newIncidentEntry.setCreatedBy(prescription.getCreatedBy());
									newIncidentEntry.setModified(prescription.getCreationDate());
//									newIncidentEntry.setModifiedBy(prescription.getPhysicianId());
									incidentEntry.setModifiedBy(prescription.getCreatedBy());
									newIncidentEntry.setEntryDate(prescription.getCreationDate());
									// save new IncidentEntry to data base
									newIncidentEntry = incidentManager.saveEntry(newIncidentEntry, IncidentManager.PRESCRIPTION);
									// set the new IncidentEntry to the prescription
									prescription.setIncidentEntry(newIncidentEntry);
									prescription.setIncidentEntryId(newIncidentEntry.getId());
									// save the prescription to data base
									prescriptionManager.savePrescription(prescription);
									//System.out.println("incidentEntry IncidentId: " + incidentEntry.getIncidentId());
									//System.out.println("incidentEntry Id: " + incidentEntry.getId());
									//System.out.println("prescription IncidentId: " + prescription.getIncidentId());
									//System.out.println("prescription incidentEntryId: " + prescription.getIncidentEntryId());
									countIECreate++;
								}
//								c++;
							}
							
//							try
//							{
//								Thread.sleep(10);
//							} catch (Exception ex) {
//							}
							i++;
						}
						logger.info("Incident Entries: " + countIEright + " were correct | " + countIESync + " synchronized  | " + countIECreate + " created");
						/////////////////////////////////////////////////////////////////////////
						// Step 3 of 4
						// Change Incident for incident entries how have prescriptions
						// get all prescriptions in database
						lastStep = 3;
						logger.info("Step " + lastStep + "/" + numberOfSteps + ": Change Incident for incident entries how have prescriptions");
						// get all prescription
						List<Integer> prescriptionList = prescriptionManager.getPrescriptionsNoSyncWithIncidentEntry();
						int prescriptionsListSize = prescriptionList.size();
						
						// set info text
						if(prescriptionsListSize > 0) infoText = Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.infoTextStepThree");
						else infoText = Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.infoTextStepThreeDone");
						
						textArea.setText(infoText);
						progressBar.setMaximum(prescriptionsListSize);

						int prescriptionNormal = 0;
						int prescriptionFixed = 0;
						i = 0;
						Incident incident;
						IncidentEntry incidentEntry;
						Prescription prescription;
						logger.info("Selected Prescriptions: " + prescriptionList.size() + " ...");
						
						for (Integer prescriptionId : prescriptionList) {
							
							// break FOR if stopButton is press
							if(stop)
							{
								//if(lastStep == 0) lastStep = 3;
								if(lastStepListSize == 0) lastStepListSize = prescriptionsListSize;
								if(lastStepCurrentItem == 0) lastStepCurrentItem = i;
								if(lastStepInfoText.equals("")) lastStepInfoText = infoText;
								break;
							}
							// get prescription
							prescription = prescriptionManager.getPrescription(prescriptionId);
							// get incident of prescription  
							incident = incidentManager.getIncident(prescription.getIncidentId());
							// get incident entry of prescription
							incidentEntry = incidentManager.getIncidentEntry(prescription.getIncidentEntryId());
							
							// if incident id of prescription and incident entry are not equal
							if(!incidentEntry.getIncidentId().equals(prescription.getIncidentId()))
							{
//								System.out.println("+++++++++++++++++++++++++++ prescriptionFixed +++++++++++++++++++++++++++");
//								System.out.println("Incident Entry IncidentId: " + incidentEntry.getIncidentId());
//								System.out.println("Prescription IncidentId: " + prescription.getIncidentId());
								prescriptionFixed++;
								//Incident incident = incidentManager.getIncident(prescription.getIncidentId());
								incidentEntry.setIncident(incident);
								incidentEntry.setIncidentId(prescription.getIncidentId());
								
								incidentEntry.setEntryTypeId(incidentEntryType.getId());
								incidentEntry.setEntryType(incidentEntryType);
								incidentEntry.setCreated(prescription.getCreationDate());
								incidentEntry.setCreatedBy(prescription.getCreatedBy());
								incidentEntry.setModified(prescription.getCreationDate());
//								incidentEntry.setModifiedBy(prescription.getPhysicianId());
								incidentEntry.setModifiedBy(prescription.getCreatedBy());
								incidentEntry.setEntryDate(prescription.getCreationDate());
								// save new IncidentEntry to data base
								//IncidentEntry incidentSaveEntry  = new IncidentEntry();
								incidentEntry = incidentManager.saveEntry(incidentEntry, IncidentManager.PRESCRIPTION);
								// set the new IncidentEntry to the prescription
								prescription.setIncidentEntry(incidentEntry);
								prescription.setIncidentEntryId(incidentEntry.getId());
								// save the prescription to data base
								prescriptionManager.savePrescription(prescription);
								
							}else{
								prescriptionNormal++;
							}
							progressBar.setValue(i);
							progressBar.setString(i + " / " + prescriptionsListSize + " | " + Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.step") + " " + lastStep + "/" + numberOfSteps);
							
//							try
//							{
//								Thread.sleep(10);
//							} catch (Exception ex) {
//							}
							i++;
						}
//						System.out.println("Gesammt: " + prescriptionFixed);
//						System.out.println("---> " + prescriptionFixed + " - fixed");
//						System.out.println("---> " + prescriptionNormal + " - normal");
						logger.info("... " + prescriptionFixed + " Prescription have been fixed | " + prescriptionNormal + " normal Prescription");
						///////////////////////////////////////////////////////////////
						// Step 4 of 4
						// delete incident witch have no incident entries
						logger.info("Step 4/4: delete incident witch have no incident entries");
						lastStep = 4;
						i = 0;
						int countDeletedIncidents = 0;
						List<Integer>patientIds = incidentManager.getNullIncident();
						int patientIdsListSize = patientIds.size();
						// set info text
						if(patientIdsListSize > 0) infoText = Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.infoTextStepFour");
						else infoText = Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.infoTextStepFourDone");
						textArea.setText(infoText);
						
						progressBar.setMaximum(patientIdsListSize);
						
						for (Integer pId : patientIds)
						{
							// break FOR if stopButton is press
							if(stop)
							{
								//if(lastStep == 0) lastStep = 4;
								if(lastStepListSize == 0) lastStepListSize = patientIdsListSize;
								if(lastStepCurrentItem == 0) lastStepCurrentItem = i;
								if(lastStepInfoText.equals("")) lastStepInfoText = infoText;
								break;
							}
							
							progressBar.setValue(i);
							//progressBar.setString("check id: " + pId + " | " + i + " / " + incidentListSize);
							progressBar.setString(i + " / " + patientIdsListSize + " | " + Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.step") + " " + lastStep + "/" + numberOfSteps);
							// look for and delete incident witch have no incident entries
							countDeletedIncidents = countDeletedIncidents + incidentManager.deleteNullIncident(pId);
//							try
//							{
//								Thread.sleep(10);
//							} catch (Exception ex) {
//							}
							i++;
						}
						logger.info("... " + countDeletedIncidents + " NULL Incidents have been deleted");
						startButton.setEnabled(true);
						stopButton.setEnabled(false);
						okButton.setEnabled(true);
						
						//if(lastStep == 0) lastStep = 4;
						if(lastStepInfoText.equals("")) lastStepInfoText = infoText;
						
						progressBar.setString(Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.labelProgressBarComplete") + " " + (System.currentTimeMillis()-runTime)/1000 + " sec. | " + Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.step") + " " + lastStep + "/" + numberOfSteps);
						textArea.setText(lastStepInfoText);
					}
				});
				thread.start();
			}
		});
		
		this.stopButton = new JButton(Translatrix.getTranslationString("dbDialogCreatePrescriptionIncidentsEntries.stopButton"));
		this.stopButton.setEnabled(false);
		this.stopButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				stop = true;
				startButton.setEnabled(true);
				stopButton.setEnabled(false);
				okButton.setEnabled(true);
			}
		});
		
		this.okButton.setText(Translatrix.getTranslationString("core.close"));
		this.okButton.setIcon(null);
	}
}