///*******************************************************************************
// * 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.Color;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.awt.event.FocusEvent;
//import java.awt.event.FocusListener;
//import java.io.File;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//import java.util.Map;
//import org.apache.log4j.Logger;
//
//import javax.swing.JButton;
//import javax.swing.JComboBox;
//import javax.swing.JDialog;
//import javax.swing.JFrame;
//import javax.swing.JLabel;
//import javax.swing.JList;
//import javax.swing.JOptionPane;
//import javax.swing.JPanel;
//import javax.swing.JScrollPane;
//import javax.swing.JTextField;
//import javax.swing.ListSelectionModel;
//import javax.swing.border.LineBorder;
//import javax.swing.event.CaretEvent;
//import javax.swing.event.CaretListener;
//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.GECAMedColors;
//import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
//import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
//import lu.tudor.santec.gecamed.core.gui.IconFetcher;
//import lu.tudor.santec.gecamed.core.gui.MainFrame;
//import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
//import lu.tudor.santec.gecamed.core.utils.controller.ControllerConfig;
//import lu.tudor.santec.gecamed.core.utils.controller.document.IController;
//import lu.tudor.santec.gecamed.core.utils.controller.document.word.WordController;
//import lu.tudor.santec.gecamed.core.utils.controller.document.writer.WriterController;
//import lu.tudor.santec.gecamed.letter.ejb.entity.beans.Letter;
//import lu.tudor.santec.gecamed.letter.ejb.entity.beans.LetterTemplate;
//import lu.tudor.santec.gecamed.letter.ejb.session.beans.LetterBean;
//import lu.tudor.santec.gecamed.letter.ejb.session.beans.LetterTemplateBean;
//import lu.tudor.santec.gecamed.letter.ejb.session.interfaces.LetterInterface;
//import lu.tudor.santec.gecamed.letter.ejb.session.interfaces.LetterTemplateInterface;
//import lu.tudor.santec.gecamed.letter.gui.LetterPanel;
//import lu.tudor.santec.gecamed.letter.gui.LetterTemplateModule;
//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.components.LimitedTextArea;
//import lu.tudor.santec.gecamed.letter.gui.placeholders.PlaceholdersConfig;
//import lu.tudor.santec.gecamed.letter.gui.settings.LetterTemplateSettings;
//import lu.tudor.santec.gecamed.letter.gui.templatelist.ListRenderer;
//import lu.tudor.santec.gecamed.letter.gui.templatelist.TemplateDetailsPanel;
//import lu.tudor.santec.gecamed.letter.gui.templatelist.TemplateListModel;
//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.patient.gui.PatientManagerModule;
//import lu.tudor.santec.i18n.Translatrix;
//
//import com.jgoodies.forms.layout.CellConstraints;
//import com.jgoodies.forms.layout.FormLayout;
//
///**
// * Dialog called by the "new Letter" Button in the Patient Module
// * Allows to select a template, contact, description and a name for a letter. A
// * After confirming the entries the CreateLetterListener class is called.
// * 
// * @author martin.heinemann@tudor.lu
// * 02.09.2008
// * 13:27:10
// *
// *
// * @version
// * <br>$Log: CreateLetterDialog.java,v $
// * <br>Revision 1.23  2013-07-15 06:18:36  ferring
// * <br>logging changed
// * <br>
// * <br>Revision 1.22  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.21  2012-02-07 13:56:49  ferring
// * <br>Name of template is chosen at start
// * <br>
// * <br>Revision 1.20  2011-08-17 08:41:16  ferring
// * <br>Office controller moved to core as they are not only used by the letter module anymore.
// * <br>
// * <br>Revision 1.19  2010-09-23 12:22:03  hermen
// * <br>now sets current user as creator of incident entry instead of current phy, which was wrong!!!
// * <br>
// * <br>http://santec.tudor.lu/trac/gecamed/ticket/643
// * <br>
// * <br>Revision 1.18  2009-12-16 11:12:15  hermen
// * <br>*** empty log message ***
// * <br>
// * <br>Revision 1.17  2009-02-25 13:26:09  hermen
// * <br>added siteID to incidents and invoices
// * <br>
// * <br>Revision 1.16  2008-10-01 07:47:47  hermen
// * <br>fixed: #184: Open addressbook when a template contains CONTACT placeholders
// * <br>
// * <br>Revision 1.15  2008-09-25 09:43:06  heinemann
// * <br>fixed copyrights
// * <br>
// * <br>Revision 1.14  2008-09-05 14:17:07  heinemann
// * <br>Fixed placeholders spelling.
// * <br>Fixed problem with placeholders that owns some trailing whitespaces. Replacing works now. In Oo. Word not tested!!!
// * <br>
// * <br>Revision 1.13  2008-09-03 10:24:14  heinemann
// * <br>*** empty log message ***
// * <br>
// *   
// */
//public class CreateLetterDialog extends JDialog {
//
//    	/**
//	 * static logger for this class
//	 */
//	private static Logger logger = Logger
//		.getLogger(CreateLetterDialog.class.getName());
//    
//	/**
//	 * 
//	 */
//	private static final long serialVersionUID = 1L;
//
//	private TemplateListModel listModel;
//
//	private JList list;
//
//	private LetterTemplateInterface manager;
//
//	private JTextField filter;
//
//	private List<LetterTemplate> templates;
//
//	private JTextField tName;
//
//	private JPanel contentPane;
//
//	private Contact contact;
//
//	private LimitedTextArea tDescription;
//
//	private JComboBox cbType;
//
//	private ArrayList<LetterTemplate> filtered_templates;
//
//	private JLabel lContactName;
//
//	/**
//	 * 
//	 */
//	public CreateLetterDialog() {
//		/* ================================================== */
//		super(MainFrame.getInstance(), true);
//		setTitle(Translatrix
//				.getTranslationString("LetterTemplateModule.dialog.title.addletter"));
//		init();
//		/* ================================================== */
//	}
//
//	public void init() {
//
//		this.setSize(550, 550);
//		this.setBackground(GECAMedColors.c_GECAMedBackground);
//		// Creating the content of the dialog
//		contentPane = new JPanel(
//				new FormLayout("15dlu,fill:90dlu:grow, 80dlu,15dlu",
//						"20dlu,30dlu,fill:90dlu:grow,20dlu,20dlu,20dlu,fill:60dlu,20dlu,20dlu"));
//		CellConstraints cc = new CellConstraints();
//		contentPane.setOpaque(false);
//
//		// Getting a session bean to receive the templates that will show up in
//		// a List
//		manager = (LetterTemplateInterface) ManagerFactory
//				.getRemote(LetterTemplateBean.class);
//
//		templates = manager.getTemplatesbyPhysician(GECAMedModule
//				.getCurrentPhysician().getId());
//
//		// A text field as filter for the list, only templates whose name
//		// matches with the text field
//		// will show up
//		JLabel lTemplate = new JLabel(
//				Translatrix
//						.getTranslationString("LetterTemplateModule.dialog.fields.select_template"));
//		contentPane.add(lTemplate, cc.xy(2, 1));
//
//		filter = new JTextField();
//		filter.addCaretListener(new CaretListener() {
//
//			public void caretUpdate(CaretEvent e) {
//				filterName();
//
//			}
//		});
//		filter.addFocusListener(new FocusListener() {
//
//			public void focusGained(FocusEvent e) {
//				list.setSelectedIndex(list.getFirstVisibleIndex());
//			}
//
//			public void focusLost(FocusEvent e) {
//			}
//
//		});
//		contentPane.add(filter, cc.xy(2, 2));
//
//		ComboBoxTypeModel cbModel = LetterTemplateModule.getInstance()
//				.getCbModel();
//		cbModel.queryTemplateTypes();
//		ComboBoxSearchTypeModel cbSearchModel = new ComboBoxSearchTypeModel(
//				cbModel);
//		cbType = new JComboBox(cbSearchModel);
//		cbType.setSelectedIndex(0);
//		cbType.addActionListener(new ActionListener() {
//
//			public void actionPerformed(ActionEvent e) {
//				filterType();
//			}
//		});
//
//		contentPane.add(cbType, cc.xy(3, 2));
//		// A little icon to identify the filter/search text field
//		JLabel lIcon = new JLabel();
//		lIcon.setIcon(GECAMedModule.getMediumIcon(GECAMedIconNames.SEARCH));
//		contentPane.add(lIcon, cc.xy(1, 2));
//
//		listModel = new TemplateListModel();
//		listModel.setTemplates(templates);
//		list = new JList(listModel);
//		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//		list.addListSelectionListener(new ListSelectionListener() {
//
//			public void valueChanged(ListSelectionEvent e) {
//			}
//		});
//		list.setCellRenderer(new ListRenderer());
//		
//		JScrollPane scrollpane = new JScrollPane(list);
//		contentPane.add(scrollpane, cc.xyw(2, 3, 2));
//
//		JLabel lOneIcon = new JLabel();
//		lOneIcon.setIcon(IconFetcher.getMediumIcon(LetterTemplateModule.class,
//				"one.png"));
//		contentPane.add(lOneIcon, cc.xy(1, 3));
//
//		JLabel lContact = new JLabel(
//				Translatrix
//						.getTranslationString("LetterTemplateModule.dialog.fields.select_contact"));
//		contentPane.add(lContact, cc.xy(2, 4));
//
//		lContactName = new JLabel(
//				Translatrix
//						.getTranslationString("LetterTemplateModule.dialog.fields.no_contact"));
//		lContactName.setForeground(Color.ORANGE);
//		contentPane.add(lContactName, cc.xy(2, 5));
//
//		JLabel lTwoIcon = new JLabel();
//		lTwoIcon.setIcon(IconFetcher.getMediumIcon(LetterTemplateModule.class,
//				"two.png"));
//		contentPane.add(lTwoIcon, cc.xy(1, 5));
//
//		JButton bContact = new JButton(
//				Translatrix
//						.getTranslationString("LetterTemplateModule.dialog.fields.load_contact"));
//		bContact.setSize(30, 10);
//		bContact.addActionListener(new ActionListener() {
//
//			public void actionPerformed(ActionEvent e) {
//				/* ================================================== */
//				String type = "";
//				if (list.getSelectedIndex() > -1) {
//					type = ((LetterTemplate) list.getSelectedValue()).getAddressType();
//					if (type == null) type = "";
//				}
//			
//				contact = ContactSearchDialog.showDialog(
//					Translatrix.getTranslationString("LetterTemplateModule.dialog.searchRecipient"),"", type);
//				if (contact != null) {
//					String name = contact.toNameString();
//					lContactName.setText(name);
//					lContactName.setForeground(new Color(83, 193, 99));
//				}
//				/* ================================================== */
//			}
//		});
//		contentPane.add(bContact, cc.xy(3, 5));
//
//		String[] param = { TemplateDetailsPanel.DESC_MAX_LENGTH + "" };
//		JLabel lDesc = new JLabel(Translatrix.getTranslationString(
//				"LetterTemplateModule.dialog.fields.description", param));
//		contentPane.add(lDesc, cc.xy(2, 6));
//
//		tDescription = new LimitedTextArea(TemplateDetailsPanel.DESC_MAX_LENGTH);
//		tDescription.setBorder(new LineBorder(Color.BLACK, 1));
//		scrollpane = new JScrollPane(tDescription);
//		contentPane.add(scrollpane, cc.xyw(2, 7, 2));
//
//		JLabel lName = new JLabel(
//				Translatrix
//						.getTranslationString("LetterTemplateModule.dialog.fields.name_letter"));
//		contentPane.add(lName, cc.xy(2, 8));
//
//		tName = new JTextField();
//		contentPane.add(tName, cc.xy(2, 9));
//
//		JButton createLetter = new JButton(
//				Translatrix
//						.getTranslationString("LetterTemplateModule.dialog.fields.addletter"));
//
//		// Listener that creates the letter based on the selected template
//		createLetter.addActionListener(new ActionListener() {
//
//			private Map<String, String> data;
//
//			private Object type;
//
//			public void actionPerformed(ActionEvent e) {
//				if (list.getSelectedIndex() > -1) {
//
//					final LetterTemplate template = (LetterTemplate) list
//							.getSelectedValue();
//
//					// New Thread, routine to open the text processing software,
//					// loading the
//					// template and saving it with the given name,
//					// or with its filename on the server. Similar to :
//					// AddTemplateDialog
//					data = PlaceholdersConfig.getPlaceholdersMap(contact, template.getVariableVersion());
//					
//					
//					new Thread() {
//
//						public void run() {
//							MainFrame.getInstance().setWaitCursor(true);
//							// Initiate text processing controller
//							IController controller = ControllerConfig
//									.getController();
//							if (controller == null) {
//							    logger.info("ControllerConfig.getController() returns NULL....stopping here");
//							    MainFrame.getInstance().setWaitCursor(false);
//							    return;
//							}
//							try {
//
//								// Getting the manager to receive the template
//								// from
//								// the server
//								LetterTemplateInterface manager = (LetterTemplateInterface) ManagerFactory
//										.getRemote(LetterTemplateBean.class);
//								byte[] filebytes = manager
//										.getTemplateBinary(template);
//
//								// Giving the template to the controller, in
//								// order to open
//								// it in the text processing software
//								if (!ControllerConfig.getLocalLetterPath()
//										.equalsIgnoreCase(
//												LetterTemplateSettings.DEFAULT))
//									controller.setDocument(filebytes,
//											ControllerConfig
//													.getLocalLetterPath());
//								else
//									controller.setDocument(filebytes);
//								controller.open();
//								
//								controller.setVariableVersion(template.getVariableVersion());
//								controller.startReplacing(data);
//								MainFrame.getInstance().setWaitCursor(false);
//								controller.waitForUserInput();
//								lu.tudor.santec.gecamed.core.utils.controller.data.State state = controller.getState();
//
//								// If the user saved the document, a new
//								// IncidentEntry is
//								// created as LetterType.
//								// The document is saved in the patients history
//								if (state.isSaved()) {
//									// Getting document from the client
//									File document = controller
//											.getDocumentbyFile();
//									String filename = document.getName();
//
//									// Saving the file on the server
////									String generated_filename = FileUtils
////											.saveGECAMedPatientFile(
////													controller.getDocument(),
////													document.getName(),
////													ServerConfig.PATIENT_FILES_DIR,
////													GECAMedModule
////															.getCurrentPatient()
////															.getId());
//									String generated_filename = manager.saveFile(
//											controller.getDocument(),
//											document.getName(),
//											GECAMedModule
//													.getCurrentPatient()
//													.getId());
//
//									if (ControllerConfig.deleteDocuments()) {
//										// Delete the local document
//										controller.deleteDocument();
//									}
//
//									// Creating the incident for the patient
//									IncidentManager iManager = (IncidentManager) ManagerFactory
//											.getRemote(IncidentManagerBean.class);
//
//									IncidentEntry ie = new IncidentEntry();
//
//									IncidentEntryType entryType = new IncidentEntryType();
//									entryType.setName(IncidentManager.LETTER);
//
//									// Attaching the Type of the file to the
//									// incident
//									ie.setEntryType(entryType);
//
//									// Create a new incident if the current is
//									// not present.
//									
//									Incident newI = new Incident(
//										GECAMedModule.getCurrentPatient().getId(),
//										MainFrame.getCurrentPhysician().getId());
//									newI.setSiteId(MainFrame.getCurrentSiteId());
//									newI = iManager.saveIncident(newI);
//									ie.setIncident(newI);
//
//									// Set created, createdby, modified,
//									// modiiedby
//									ie.setCreated(new Date());
//									ie.setCreatedBy(GECAMedModule
//											.getCurrentUser().getId());
//									ie.setModified(new Date());
//									ie.setModifiedBy(GECAMedModule
//											.getCurrentUser().getId());
//
//									ie.setTextContent(tDescription.getText());
//
//									// Set the file name
//									if (tName.getText().equals("")) {
//										ie.setFileName(filename);
//									} else {
//										ie.setFileName(tName.getText());
//									}
//									ie.setFileSize(document.length());
//
//									// save
//									ie.setOriginalFilename(generated_filename);
//									ie = iManager.saveEntry(ie,
//											IncidentManager.LETTER);
//
//									// Saving letter corresponding to the
//									// incident entry
//									int incedentEntryId = ie.getId();
//
//									LetterInterface letterManager = (LetterInterface) ManagerFactory
//											.getRemote(LetterBean.class);
//
//									Letter letter = new Letter();
//									letter.setIncidentEntryID(incedentEntryId);
//									if (controller instanceof WordController) {
//										letter
//												.setMimetype(ControllerConfig.MIME_WORD);
//									}
//									if (controller instanceof WriterController) {
//										letter
//												.setMimetype(ControllerConfig.MIME_WRITER);
//									}
//
//									type = template.getType();
//									letter.setType((String) type);
//
//									letterManager.addLetter(letter);
//
//									LetterPanel.getInstance().getCbModel()
//											.queryLetterTypes();
//
//								} else {
//									if (ControllerConfig.deleteDocuments()) {
//										// Delete the local document
//										controller.deleteDocument();
//									}
//								}
//								PatientManagerModule.getInstance()
//										.getPatientPanel()
//										.reloadHistory();
//							} catch (Exception e) {
//								e.printStackTrace();
//								MainFrame.getInstance().setWaitCursor(false);
//								JOptionPane
//										.showMessageDialog(
//												contentPane,
//												Translatrix
//														.getTranslationString("LetterTemplateModule.dialog.error.letteropening"),
//												Translatrix
//														.getTranslationString("LetterTemplateModule.dialog.error.title"),
//												JOptionPane.ERROR_MESSAGE);
//							}
//						}
//
//					}.start();
//
//					dispose();
//
//				} else {
//					JOptionPane
//							.showMessageDialog(
//									contentPane,
//									Translatrix
//											.getTranslationString("LetterTemplateModule.dialog.error.notemplate"),
//									Translatrix
//											.getTranslationString("LetterTemplateModule.dialog.error.title"),
//									JOptionPane.ERROR_MESSAGE);
//				
//				}
//			}
//		});
//		contentPane.add(createLetter, cc.xy(3, 9));
//
//		JLabel lThreeIcon = new JLabel();
//		lThreeIcon.setIcon(IconFetcher.getMediumIcon(
//				LetterTemplateModule.class, "three.png"));
//		contentPane.add(lThreeIcon, cc.xy(1, 9));
//
//		this.setContentPane(contentPane);
//		filter.setFocusable(true);
//		this.setLocationRelativeTo(MainFrame.getInstance());
//		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//		this.setVisible(true);
//	}
//
//	protected void filterType() {
//		ArrayList<LetterTemplate> result = new ArrayList<LetterTemplate>();
//		if (cbType.getSelectedItem().toString().equalsIgnoreCase(
//				LetterTemplateModule.ALL)) {
//			filtered_templates = (ArrayList<LetterTemplate>) templates;
//		} else {
//			for (int i = 0; i < templates.size(); i++) {
//				if (templates.get(i).getType().toLowerCase().equals(
//						cbType.getSelectedItem().toString().toLowerCase())) {
//					result.add(templates.get(i));
//				}
//			}
//			filtered_templates = result;
//		}
//		filterName();
//	}
//
//	protected void filterName() {
//		ArrayList<LetterTemplate> result = new ArrayList<LetterTemplate>();
//
//		// The main function for the filter of the list containing templates
//		if (filter.getText().equalsIgnoreCase("")) {
//			listModel.setTemplates(filtered_templates);
//			list.setSelectedIndex(list.getFirstVisibleIndex());
//		} else {
//			for (int i = 0; i < filtered_templates.size(); i++) {
//				if (filtered_templates.get(i).getName().toLowerCase()
//						.startsWith(filter.getText().toLowerCase())) {
//					result.add(filtered_templates.get(i));
//				}
//			}
//			listModel.setTemplates(result);
//		}
//	}
//	
//	protected void setNameAndDescription ()
//	{
//		if (list.getSelectedIndex() > -1)
//		{
//			tDescription.setText(((LetterTemplate) 
//					list.getSelectedValue()).getDescription());
//			tName.setText(((LetterTemplate) 
//					list.getSelectedValue()).getName());
//		}
//	}
//}
