package lu.tudor.santec.gecamed.esante.gui.dialogs;

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

import lu.tudor.santec.gecamed.esante.ejb.entity.beans.CdaDocument;
import lu.tudor.santec.gecamed.esante.ejb.session.beans.CDAManagerBean;
import lu.tudor.santec.gecamed.esante.ejb.session.interfaces.CDAManager;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Logger;

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

/**
 * @author jens.ferring(at)tudor.lu
 * 
 * @version
 * <br>$Log: ClearCdaDocumentsDialog.java,v $
 * <br>Revision 1.2  2014-02-04 10:08:40  ferring
 * <br>eSante ID management completed
 * <br>Only those documents will be shown, that are retrieved by the RSQ
 * <br>
 * <br>Revision 1.1  2014-01-21 14:32:05  ferring
 * <br>myDSP configuration can be changed and reloaded.
 * <br>The clean CDA files on server function was added
 * <br>
 */

public class ClearCdaDocumentsDialog extends ESanteDialog implements Runnable
{
	/* ======================================== */
	// CONSTANTS
	/* ======================================== */
	
	private static final long	serialVersionUID	= 1L;
	
	private static final String TITLE_TRANSLATION_KEY	= "esante.managementPanel.preferencesPanel.clearCda.title";
	
	
	
	/* ======================================== */
	// MEMBERS
	/* ======================================== */
	
	/** the logger Object for this class */
	private static Logger	logger = Logger.getLogger(ClearCdaDocumentsDialog.class.getName());
	
	
	private boolean			keepRunning;
	
	private JProgressBar	progressBar;
	
	private JButton			startButton;
	
	private JButton			stopButton;
	
	private	Thread			worker;

	private	int				noOfDocs2Delete;
	
	private	int				noOfDocsDeleted;
	
	
	
	/* ======================================== */
	// CONSTRUCTORS
	/* ======================================== */
	
	private ClearCdaDocumentsDialog (JDialog owner)
	{
		super(owner, Translatrix.getTranslationString(TITLE_TRANSLATION_KEY), OK_BUTTON_MODE);
		init();
	}
	
	
	private ClearCdaDocumentsDialog (JFrame owner)
	{
		super(owner, Translatrix.getTranslationString(TITLE_TRANSLATION_KEY), OK_BUTTON_MODE);
		init();
	}
	
	
	
	/* ======================================== */
	// CLASS BODY
	/* ======================================== */
	
	public static void showDialog (Window owner)
	{
		ClearCdaDocumentsDialog	dialog;
		
		
		if (owner instanceof JDialog)
			dialog	= new ClearCdaDocumentsDialog((JDialog)owner);
		else
			dialog	= new ClearCdaDocumentsDialog((JFrame)owner);
		
		dialog.showDialog();
	}
	
	
	public void run ()
	{
		keepRunning	= true;
		startButton.setEnabled(false);
		stopButton.setEnabled(true);
		
		try
		{
			logger.info("START cleaning CDA document files from server");
			cleanDocuments();
		}
		finally
		{
			if (noOfDocs2Delete == 0)
			{
				progressBar.setString(Translatrix.getTranslationString(
						"esante.managementPanel.preferencesPanel.clearCda.noFiles2Delete"));
			}
			else if (!keepRunning)
			{
				progressBar.setString(Translatrix.getTranslationString(
						"esante.managementPanel.preferencesPanel.clearCda.progressStopped",
						new String[] { String.valueOf(noOfDocsDeleted), String.valueOf(noOfDocs2Delete) }));
				logger.info("STOPPED cleaning CDA document files from server");
			}
			else if (noOfDocsDeleted == noOfDocs2Delete)
			{
				progressBar.setString(Translatrix.getTranslationString(
						"esante.managementPanel.preferencesPanel.clearCda.progressDone",
						new String[] { String.valueOf(noOfDocsDeleted), String.valueOf(noOfDocs2Delete) }));
				logger.info("FINISHED cleaning CDA document files from server");
			}
			else
			{
				logger.warn("ERROR while cleaning CDA document files from server");
			}
			
			keepRunning = false;
			startButton.setEnabled(true);
			stopButton.setEnabled(false);
		}
	}
	
	
	
	/* ======================================== */
	// HELP METHODS
	/* ======================================== */
	
	private void init ()
	{
		CellConstraints	cc	= new CellConstraints();
		JLabel	warningLabel	= new JLabel(Translatrix.getTranslationString(
				"esante.managementPanel.preferencesPanel.clearCda.warning"));
		
		
		warningLabel.setOpaque(false);
		
		progressBar	= new JProgressBar();
		progressBar.setStringPainted(true);
		progressBar.setMinimum(0);
		
		startButton	= new JButton(new AbstractAction(
				Translatrix.getTranslationString("esante.managementPanel.preferencesPanel.clearCda.start"))
		{
			private static final long	serialVersionUID	= 1L;

			public void actionPerformed (ActionEvent e)
			{
				start();
			}
		});
		
		stopButton	= new JButton(new AbstractAction(
				Translatrix.getTranslationString("esante.managementPanel.preferencesPanel.clearCda.stop"))
		{
			private static final long	serialVersionUID	= 1L;

			public void actionPerformed (ActionEvent e)
			{
				stop();
			}
		});
		
		mainPanel.setLayout(new FormLayout(
				// columns
				" 5px,f:p,"	+	// start button
				" f:p:g,"	+	// free space
				" f:p,5px",		// stop button
				// rows
				" 5px,f:p," +	// warning	
				"15px,f:p," +	// progress bar	
				" 5px,f:p," +	// start & stop button
				" 5px"));
		
		int row = 0;
		mainPanel.add(warningLabel,	cc.xyw(2, row+=2, 3));
		mainPanel.add(progressBar,	cc.xyw(2, row+=2, 3));
		mainPanel.add(startButton,	cc.xy(2, row+=2));
		mainPanel.add(stopButton,	cc.xy(4, row));
	}
	
	
	private void showDialog ()
	{
		startButton.setEnabled(true);
		stopButton.setEnabled(false);
		pack();
		showCenteredDialog();
	}
	
	
	private void start ()
	{
		synchronized (this)
		{
			if (worker != null && worker.isAlive())
				return;
			
			worker		= new Thread(this, "CDA_file_cleaner");
		}
		
		worker.start();
	}
	
	
	private void stop ()
	{
		keepRunning	= false;
		stopButton.setEnabled(false);
	}
	
	
	private void cleanDocuments ()
	{
		CDAManager			manager			= CDAManagerBean.getInstance();
		List<CdaDocument>	documentBufferList	= null;
		Long				count;
		String				progressString;
		CdaDocument			document2delete;
		
		
		if (!keepRunning)
			return;
		
		progressBar.setValue(0);
		progressBar.setString(Translatrix.getTranslationString(
				"esante.managementPanel.preferencesPanel.clearCda.prepareCleaning"));
		
		// count CDAs to delete
		count	= manager.countDownloadedNotIntegratedCdaDocuments();
		
		if (count == null)
			noOfDocs2Delete	= 0;
		else
			noOfDocs2Delete	= count.intValue();
		
		if (noOfDocs2Delete == 0)
			return;
		
		progressBar.setMaximum(noOfDocs2Delete);
		progressBar.setValue(0);
		
		progressString	= Translatrix.getTranslationString(
				"esante.managementPanel.preferencesPanel.clearCda.progress")
				.replace("$1", String.valueOf(noOfDocs2Delete));
		
		for (noOfDocsDeleted = 0; keepRunning && noOfDocsDeleted < noOfDocs2Delete; noOfDocsDeleted++)
		{
			// update progress bar string
			progressBar.setString(progressString.replace("$0", String.valueOf(noOfDocsDeleted)));
			progressBar.setValue(noOfDocsDeleted);
			
			if (documentBufferList == null || documentBufferList.isEmpty())
			{
				documentBufferList	= manager.getDownloadedNotInegratedCdaDocuments(noOfDocsDeleted);
				if (documentBufferList == null || documentBufferList.isEmpty())
					// no more documents to delete found
					break;
			}
			
			// delete the next CDA file
			document2delete = documentBufferList.remove(0);
			logger.info(new StringBuilder("deleting CDA ")
					.append(document2delete.getTitle())
					.append(" (")
					.append(document2delete.getServerFileName())
					.append(") of DSP with ID ")
					.append(document2delete.getDspId()));
			manager.deleteCdaFile(document2delete);
		}
		progressBar.setString(progressString.replace("$0", String.valueOf(noOfDocsDeleted)));
		progressBar.setValue(noOfDocsDeleted);
	}
	
	
	@Override
	public void okActionCalled ()
	{
		stop();
		super.okActionCalled();
	}
	
	
	@Override
	public void closeActionCalled ()
	{
		stop();
		super.closeActionCalled();
	}
}
