/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed 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 (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
package lu.tudor.santec.gecamed.letter.gui.dialogs;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import lu.tudor.santec.gecamed.addressbook.ejb.entity.beans.Contact;
import lu.tudor.santec.gecamed.addressbook.gui.list.ContactSearchDialog;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.controller.document.DocumentController;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialog;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.letter.ejb.entity.beans.LetterTemplate;
import lu.tudor.santec.gecamed.letter.ejb.session.beans.LetterTemplateBean;
import lu.tudor.santec.gecamed.letter.ejb.session.interfaces.LetterTemplateInterface;
import lu.tudor.santec.gecamed.letter.gui.actions.CreateLetterAction;
import lu.tudor.santec.gecamed.letter.gui.components.ComboBoxSearchTypeModel;
import lu.tudor.santec.gecamed.letter.gui.components.ComboBoxTypeModel;
import lu.tudor.santec.gecamed.letter.gui.templatelist.ListRenderer;
import lu.tudor.santec.gecamed.letter.gui.templatelist.TemplateListModel;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 * Dialiog to create a letter from the letter templates list.
 * 
 * @author martin.heinemann@tudor.lu
 * 02.09.2008
 * 13:58:40
 *
 *
 * @version
 * <br>$Log: NewLetterDialog.java,v $
 * <br>Revision 1.15  2013-12-27 18:09:25  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.14  2013-07-15 06:18:36  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.13  2013-03-22 10:49:35  ferring
 * <br>store position and size of the dialog by user
 * <br>minimum size added
 * <br>scroll pane grows now, when resizing
 * <br>
 * <br>Revision 1.12  2013-02-14 08:15:18  ferring
 * <br>incident selection added to new letters and improved for files
 * <br>
 * <br>Revision 1.11  2013-01-08 07:00:33  ferring
 * <br>LetterTemplate filter for new letter changed
 * <br>
 * <br>Revision 1.10  2013-01-07 13:28:23  ferring
 * <br>Type filter in letter template list shows now only those templates types, that of which exists templates that are available for the physician.
 * <br>Type chooser of the meta data shows now all template types with existing templates, independent of the current physician and of the types that exist for existing letters.
 * <br>
 * <br>Revision 1.9  2012-12-14 09:48:21  ferring
 * <br>Interface IController replaced by abstract class DocumentController
 * <br>Function added to update placeholders in letter template
 * <br>
 * <br>Revision 1.8  2012-11-26 07:56:14  ferring
 * <br>New placeholders are introduced to the letter module
 * <br>The replacement algorithm in Word- and WriterCotnroller has been changed
 * <br>Multicontacts are prepared, but not yet implemented
 * <br>
 * <br>Revision 1.7  2012-02-07 13:56:49  ferring
 * <br>Name of template is chosen at start
 * <br>
 * <br>Revision 1.6  2008-12-15 11:03:38  hermen
 * <br>fixed bug in contact address
 * <br>
 * <br>Revision 1.5  2008-12-05 17:34:23  heinemann
 * <br>moved some basic classes to lu.tudor.santec.widgets
 * <br>
 * <br>Revision 1.4  2008-10-01 07:47:47  hermen
 * <br>fixed: #184: Open addressbook when a template contains CONTACT placeholders
 * <br>
 * <br>Revision 1.3  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.2  2008-09-15 12:06:45  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2008-09-03 10:24:14  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
public class NewLetterDialog extends GECAMedBaseDialog
{
	private static final long serialVersionUID = 1L;
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(NewLetterDialog.class.getName());
	
	private static LetterTemplateInterface	templateManager;
	
	
	private NewLetterDialogPanel panel;
	private TemplateListModel listModel;
	
//	private List<LetterTemplate> templates;
	
//	private List<LetterTemplate> filtered_templates;
	private List<Contact> selectedContacts;
	
	/**
	 * 
	 */
	public NewLetterDialog () {
		/* ================================================== */
		super(Translatrix.getTranslationString("LetterTemplateModule.dialog.title.addletter"),
							true, true, false);
		setResizingOptions(RESIZING_ALL);
		
		this.enableCancelKeyMapping(false);
		this.enableOkKeyMapping(false);
		
		/* ------------------------------------------------------- */
		this.panel = new NewLetterDialogPanel();
		
		addMainPanel(panel);
		initData();
		initActions();
		pack();
		setMinimumSize(getPreferredSize());
		/* ================================================== */
	}
	
	/**
	 * 
	 */
	private void initActions() {
		/* ================================================== */
		panel.categoryBox.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				filter();
			}
		});
		/* ------------------------------------------------------- */
		
		
//		panel.contactPanel.addActionListener(new ActionListener() {
//
//			public void actionPerformed(ActionEvent e) {
//				/* ================================================== */
//				String type = "";
//				if (panel.templateList.getSelectedIndex() > -1) {
//					/* ------------------------------------------------------- */
//					type = ((LetterTemplate) panel.templateList.getSelectedValue()).getAddressType();
//					if (type == null) type = "";
//					/* ------------------------------------------------------- */
//				}
//			
//				selectedContact = ContactSearchDialog.showDialog(
//						Translatrix.getTranslationString("LetterTemplateModule.dialog.searchRecipient"),
//						"", type, );
//				if (selectedContact != null) {
//					/* ------------------------------------------------------- */
//					String name = selectedContact.toNameString();
//					panel.contactLabel.setText(name);
//					panel.contactLabel.setForeground(new Color(83, 193, 99));
//					/* ------------------------------------------------------- */
//					// add the contact to the name
//					/* ------------------------------------------------------- */
////					if (panel.nameField.getText() != null && !"".equals(panel.nameField.getText().trim()))
//						panel.nameField.setText(((LetterTemplate) panel.templateList.getSelectedValue()).getName() + " - " + name );
////					else
////						panel.nameField.setText(name);
//					/* ------------------------------------------------------- */
//				}
//				/* ================================================== */
//			}
//		});
		
		/* ------------------------------------------------------- */
		// selection listener for the list
		/* ------------------------------------------------------- */
		panel.templateList.addListSelectionListener(new ListSelectionListener() {

			public void valueChanged(ListSelectionEvent e) 
			{
				setNameAndDescription();
			}
		});
		/* ------------------------------------------------------- */
		// mouselistener for the list
		/* ------------------------------------------------------- */
		panel.templateList.addMouseListener(new MouseAdapter() {

			/* (non-Javadoc)
			 * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
			 */
			@Override
			public void mouseClicked(MouseEvent e) {
				/* ====================================================== */
				if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
					/* ------------------------------------------------------- */
					useTemplate();
					/* ------------------------------------------------------- */
				}
				/* ====================================================== */
			}
			
		});
		
		
		/* ------------------------------------------------------- */
		// filter
		/* ------------------------------------------------------- */
		panel.searchField.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ====================================================== */
				filter();
				/* ====================================================== */
			}
			
		});
		
		/* ------------------------------------------------------- */
		// create letter action
		/* ------------------------------------------------------- */
		this.okButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ====================================================== */
				if (panel.templateList.getSelectedIndex() > -1) {
					/* ------------------------------------------------------- */
					useTemplate();
				/* ------------------------------------------------------- */
				}
				
				
				/* ====================================================== */
			}
		});
		
		
		
		
		this.cancelButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ====================================================== */
				setVisible(false);
				/* ====================================================== */
			}
			
		});
		/* ================================================== */
	}
	
	
	/**
	 * Uses the selected template, opens the TPS and closes the dialog
	 */
	private void useTemplate() 
	{
		LetterTemplate ltmp = (LetterTemplate) panel.templateList.getSelectedValue();
		
		if (ltmp.getRequiresContact())
		{
			String type = ltmp.getAddressType();
		    if (type == null) type = "";
		    selectedContacts = ContactSearchDialog.showDialog(
		    		Translatrix.getTranslationString("LetterTemplateModule.dialog.searchRecipient"),
		    		"", type, ltmp.getPlaceholderVersion() > DocumentController.PH_VERSION_OLD);
		    
		    if (selectedContacts == null || selectedContacts.isEmpty())
		    	return;
		}
		else
			selectedContacts = null;
	    
		CreateLetterAction ca = new CreateLetterAction(ltmp, selectedContacts, 
				panel.nameField.getText(), NewLetterDialog.this.panel, 
				(Incident)panel.incidentBox.getSelectedItem());
		ca.create();
		setVisible(false);
	}
	
	
	private void initData() {
		/* ================================================== */
//		try {
//			/* ------------------------------------------------------- */
//			// Getting a session bean to receive the templates that will show up in
//			// a List
//			templates = getTemplateManager().getTemplatesByPhysycian(GECAMedModule.getCurrentPhysician().getId());
//			/* ------------------------------------------------------- */
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		/* ------------------------------------------------------- */
		// init the category box
		/* ------------------------------------------------------- */
		ComboBoxTypeModel cbModel = new ComboBoxSearchTypeModel();
		cbModel.queryTemplateTypes();
		
		panel.incidentBox.fill(PatientManagerModule.getInstance().getPatientPanel()
				.getHistoryDataAgent().getIncidents().values());
		
		panel.categoryBox.setModel(cbModel);
		try {
			panel.categoryBox.setSelectedIndex(0);
		} catch (Exception e) {
		}
		/* ------------------------------------------------------- */
		// init the template list
		/* ------------------------------------------------------- */
		this.listModel = new TemplateListModel();
//		listModel.setTemplates(templates);
		
		panel.templateList.setModel(listModel);
		/* ------------------------------------------------------- */
		panel.templateList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		panel.templateList.setCellRenderer(new ListRenderer());
		/* ------------------------------------------------------- */
		
		// select first template
		try 
		{
		    panel.templateList.setSelectedIndex(0);		    
		} 
		catch (Exception e) 
		{
			logger.log(Level.INFO, "No letter templates available");
		}
		
		panel.contactLabel.setText(
				Translatrix.getTranslationString("LetterTemplateModule.dialog.fields.no_contact"));
		
		setNameAndDescription();
		
		filter();
		/* ================================================== */
	}
	
	
	protected void filter ()
	{
		int						typeIndex	= panel.categoryBox.getSelectedIndex();
		String					typeFilter	= typeIndex > 0 
				? (String) panel.categoryBox.getSelectedItem() : null;
		String					nameFilter	= panel.searchField.getText();
		Physician				physician	= GECAMedModule.getCurrentPhysician();;
		List<LetterTemplate>	templates;
		
		
		templates = getTemplateManager().getFilteredTemplates(
				physician != null ? physician.getId() : null,
				typeFilter,
				nameFilter != null && nameFilter.trim().length() > 0 
						? nameFilter.toLowerCase()	: null);
		
		listModel.setTemplates(templates);
	}
	
	
//	protected void filterType() {
//		/* ================================================== */
//		ArrayList<LetterTemplate> result = new ArrayList<LetterTemplate>();
//		if (panel.templateCategoryBox.getSelectedItem().toString().equals("")) {
//			/* ------------------------------------------------------- */
//			filtered_templates = templates;
//			/* ------------------------------------------------------- */
//		} else {
//			/* ------------------------------------------------------- */
//			for (int i = 0; i < templates.size(); i++) {
//				/* ------------------------------------------------------- */
//				if (templates.get(i).getType().toLowerCase().equals(
//						panel.templateCategoryBox.getSelectedItem().toString().toLowerCase())) {
//					/* ------------------------------------------------------- */
//					result.add(templates.get(i));
//					/* ------------------------------------------------------- */
//				}
//				/* ------------------------------------------------------- */
//			}
//			filtered_templates = result;
//			/* ------------------------------------------------------- */
//		}
//		filterName();
//		/* ================================================== */
//	}
//
//	protected void filterName() {
//		/* ================================================== */
//		ArrayList<LetterTemplate> result = new ArrayList<LetterTemplate>();
//		
//		if (filtered_templates == null) 
//			filtered_templates = templates;
//		
//		/* ------------------------------------------------------- */
//		// The main function for the filter of the list containing templates
//		/* ------------------------------------------------------- */
//		if (panel.searchField.getText().equalsIgnoreCase("")) {
//			/* ------------------------------------------------------- */
//			listModel.setTemplates(filtered_templates);
//			panel.templateList.setSelectedIndex(panel.templateList.getFirstVisibleIndex());
//			/* ------------------------------------------------------- */
//		} else {
//			/* ------------------------------------------------------- */
//			for (int i = 0; i < filtered_templates.size(); i++) {
//				/* ------------------------------------------------------- */
//				if (filtered_templates.get(i).getName().toLowerCase()
//						.startsWith(panel.searchField.getText().toLowerCase())) {
//					result.add(filtered_templates.get(i));
//				}
//				/* ------------------------------------------------------- */
//			}
//			listModel.setTemplates(result);
//			/* ------------------------------------------------------- */
//		}
//		setNameAndDescription();
//		/* ================================================== */
//	}
	
	
	private void setNameAndDescription ()
	{
		if (panel.templateList.getSelectedIndex() > -1) 
		{
			LetterTemplate ltmp = (LetterTemplate) panel.templateList.getSelectedValue();
			
			// enable contact button
			if (ltmp.getRequiresContact() != null && ltmp.getRequiresContact() == true)
				panel.contactPanel.enablePanel(true);
			else
				panel.contactPanel.enablePanel(false);
			
			// create a name out of the selected template
			panel.nameField.setText(ltmp.getName());
		}
	}
	
	
	private LetterTemplateInterface getTemplateManager ()
	{
		if (templateManager == null)
			templateManager	= (LetterTemplateInterface) 
					ManagerFactory.getRemote(LetterTemplateBean.class);
		
		return templateManager;
	}
}
