/*******************************************************************************
 * 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.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;

import lu.tudor.santec.gecamed.addressbook.ejb.session.beans.AddressbookManager;
import lu.tudor.santec.gecamed.addressbook.ejb.session.interfaces.AddressbookInterface;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.ModuleManager;
import lu.tudor.santec.gecamed.core.gui.controller.ControllerConfig;
import lu.tudor.santec.gecamed.core.gui.utils.SimpleListModel;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialogImpl;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.letter.ejb.entity.beans.LetterPlaceholder;
import lu.tudor.santec.gecamed.letter.gui.actions.CreateTemplateAction;
import lu.tudor.santec.gecamed.letter.gui.components.ComboBoxTypeModel;
import lu.tudor.santec.gecamed.letter.gui.components.SortedListModel;
import lu.tudor.santec.gecamed.letter.gui.placeholders.PlaceholdersConfig;
import lu.tudor.santec.i18n.Translatrix;

import com.jgoodies.validation.Severity;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.message.SimpleValidationMessage;

/**
 * @author martin.heinemann@tudor.lu
 * 25.08.2008
 * 10:51:46
 *
 *
 * @version
 * <br>$Log: NewTemplateDialog.java,v $
 * <br>Revision 1.9  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.8  2013-01-03 09:47:50  ferring
 * <br>Extends now GECAMedBaseDialogImpl instead of GECAMedBaseDialog
 * <br>
 * <br>Revision 1.7  2012-12-14 14:57:07  ferring
 * <br>Entries in placeholder type combo box are now alphabetically sorted
 * <br>
 * <br>Revision 1.6  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.5  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.4  2009-05-06 15:59:07  heinemann
 * <br>added some new placeholders
 * <br>
 * <br>Revision 1.3  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.2  2008-09-03 10:24:14  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2008-08-27 15:34:53  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
public class NewTemplateDialog extends GECAMedBaseDialogImpl {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private NewTemplateDialogPanel panel;
	
	private Map<String, List<LetterPlaceholder>> existingPlaceholder;
	private Vector<LetterPlaceholder> selectedPlaceholders = new Vector<LetterPlaceholder>();
	private SimpleListModel<LetterPlaceholder> repositoryListModel;
	private SimpleListModel<LetterPlaceholder> selectedListModel;
	
	private File importFile = null;
	
	public NewTemplateDialog() {
		/* ================================================== */
		super(MainFrame.getInstance(),
				Translatrix.getTranslationString("LetterTemplateModule.dialog.title.addtemplate"), 
				GECAMedBaseDialogImpl.OK_CANCEL_BUTTON_MODE, 
				new NewTemplateDialogPanel());
		
		this.existingPlaceholder = PlaceholdersConfig.getPlaceHolders();
		
//		this.enableCancelKeyMapping(false);
//		this.enableOkKeyMapping(false);
		
//		initButtonActions();
		
//		this.panel = new NewTemplateDialogPanel();
//		this.addMainPanel(panel);
		this.panel = (NewTemplateDialogPanel) super.mainPanel;
		
		initData();
		initActions();
		updateRepositoryList();
		this.pack();
		/* ================================================== */
	}
	
	
	@Override
	public void okActionCalled()
	{
		ValidationResult result = doValidate();
		CreateTemplateAction ca;
		
		
		if ((result != null && result.size() > 0)) 
		{
			panel.validationResultModel.setResult(result);
			pack();
			return;
		} 
		else 
		{
			setVisible(false);
			ca = new CreateTemplateAction(selectedPlaceholders,
					(String) panel.templateCategoryBox.getSelectedItem(),
					importFile,
					panel.nameField.getText(),
					(String) panel.contactCategoryBox.getSelectedItem(),
					NewTemplateDialog.this);
			ca.create();
		}
	}
	
	
	
//	/**
//	 * 
//	 */
//	private void initButtonActions() {
//		/* ================================================== */
//		this.okButton.addActionListener(new ActionListener() {
//
//			public void actionPerformed(ActionEvent e) {
//				/* ====================================================== */
//				ValidationResult result = doValidate();
//				if ((result != null && result.size() > 0)) {
//					
//					panel.validationResultModel.setResult(result);
//					pack();
//					return;
//				} else {
//					/* ------------------------------------------------------- */
//					setVisible(false);
//					CreateTemplateAction ca = new CreateTemplateAction(selectedPlaceholders,
//															(String) panel.templateCategoryBox.getSelectedItem(),
//															importFile,
//															panel.nameField.getText(),
//															(String) panel.contactCategoryBox.getSelectedItem(),
//															NewTemplateDialog.this);
//					ca.create();
//					/* ------------------------------------------------------- */
//				}
//				/* ====================================================== */
//			}
//			
//		});
//		
//		this.cancelButton.addActionListener(new ActionListener() {
//
//			public void actionPerformed(ActionEvent e) {
//				/* ====================================================== */
//				setVisible(false);
//				/* ====================================================== */
//			}
//			
//		});
//		/* ================================================== */
//	}
	
	
	/**
	 * @return
	 */
	private ValidationResult doValidate() {
		/* ================================================== */
		ValidationResult validationResult = new ValidationResult();
		
		/* ------------------------------------------------------- */
		// if there is no name, error 
		/* ------------------------------------------------------- */
		if (panel.nameField.getText() == null || panel.nameField.getText().trim().equals("")) {
			/* ------------------------------------------------------- */
			validationResult.add(new SimpleValidationMessage(
					Translatrix.getTranslationString("LetterTemplateModule.add.error.name"), Severity.ERROR));
			/* ------------------------------------------------------- */
		}
		// ...
		return validationResult;
		/* ================================================== */
	}
	
	
	/**
	 * load data into the lists and comboboxes 
	 */
	private void initData() {
		/* ================================================== */
		// init the category box
		/* ------------------------------------------------------- */
		ComboBoxTypeModel cbModel = new ComboBoxTypeModel();
		cbModel.queryAllTemplateTypes();
		panel.templateCategoryBox.setModel(cbModel);
		try {
			panel.templateCategoryBox.setSelectedIndex(0);
		} catch (Exception e) {
		}
		panel.templateCategoryBox.setEditable(true);
		/* ------------------------------------------------------- */
		// set a model to the placeholder repository list
		/* ------------------------------------------------------- */
		this.repositoryListModel = new SimpleListModel<LetterPlaceholder>();
		panel.placeHolderRepositoryList.setModel(this.repositoryListModel);
		/* ------------------------------------------------------- */
		// set a model to the placeholderSelectList
		/* ------------------------------------------------------- */
		this.selectedListModel = new SimpleListModel<LetterPlaceholder>();
		panel.selectedPlaceHolderList.setModel(selectedListModel);
		/* ------------------------------------------------------- */
		// the placeholders
		/* ------------------------------------------------------- */
		// categories in the combobox
		/* ------------------------------------------------------- */
		((SortedListModel)panel.placeHolderCategoryBox.getModel()).addAll(existingPlaceholder.keySet());
//		for (String cat : existingPlaceholder.keySet()) {
//			panel.placeHolderCategoryBox.addItem(cat);
//		}
		
		/* ------------------------------------------------------- */
		// try to load the adressbokk types from the server
		/* ------------------------------------------------------- */
		// first check if the addressbook module is present
		/* ------------------------------------------------------- */
		if (ModuleManager.getModule("Addressbook") != null) {
			/* ------------------------------------------------------- */
			panel.contactCategoryBox.setVisible(  true);
			
			try {
				/* ------------------------------------------------------- */
				// get the sessionbean of the addressbook modul
				/* ------------------------------------------------------- */
				AddressbookInterface addressManager = (AddressbookInterface) 
									ManagerFactory.getRemote(AddressbookManager.class);
				
				Collection<String> addressTypes = addressManager.getContactTypes();
				/* ------------------------------------------------------- */
				// fill the box
				/* ------------------------------------------------------- */
				panel.contactCategoryBox.removeAllItems();
				panel.contactCategoryBox.addItem("");
				for (String aType : addressTypes)
					panel.contactCategoryBox.addItem(aType);
				/* ------------------------------------------------------- */
			} catch (Exception e) {
				e.printStackTrace();
			}
 			/* ------------------------------------------------------- */
		} else {
			/* ------------------------------------------------------- */
			// we hide the field
			/* ------------------------------------------------------- */
			panel.contactCategoryBox.setVisible(  false);
			/* ------------------------------------------------------- */
		}
		/* ================================================== */
	}
	
	/**
	 * Init the gui actions
	 */
	private void initActions() {
		/* ================================================== */
		// the change action for the placeholder category combobox
		/* ------------------------------------------------------- */
		panel.placeHolderCategoryBox.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ====================================================== */
				updateRepositoryList();
				/* ====================================================== */
			}
		});
		/* ------------------------------------------------------- */
		// the actions for the move buttons
		/* ------------------------------------------------------- */
		panel.selectButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ====================================================== */
				moveToSelect();
				/* ====================================================== */
			}
			
		});
		/* ------------------------------------------------------- */
		// the selectAll button
		/* ------------------------------------------------------- */
		panel.selectAllButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ====================================================== */
				// move selected items from the repository to the selection list
				/* ------------------------------------------------------- */
				Vector<LetterPlaceholder> selection = repositoryListModel.getData();
				/* ------------------------------------------------------- */
				if (selection == null || selection.size() < 1)
					return;
				/* ------------------------------------------------------- */
				selectedPlaceholders.addAll(selection);
				updateRepositoryList();
				updateSelectedList();
				/* ====================================================== */
			}
		});
		/* ------------------------------------------------------- */
		// the remove button
		/* ------------------------------------------------------- */
		panel.deselectButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ====================================================== */
				removeFromSelect();
				/* ====================================================== */
			}
		});
		/* ------------------------------------------------------- */
		// the removeAll button
		/* ------------------------------------------------------- */
		panel.deselectAllButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ====================================================== */
				// move selected items from the repository to the selection list
				/* ------------------------------------------------------- */
				selectedPlaceholders.clear();
				updateRepositoryList();
				updateSelectedList();
				/* ====================================================== */
			}
		});
		/* ------------------------------------------------------- */
		// mouselistener for the lists
		/* ------------------------------------------------------- */
		panel.placeHolderRepositoryList.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) {
					/* ------------------------------------------------------- */
					moveToSelect();
					/* ------------------------------------------------------- */
				}
				/* ====================================================== */
			}
		});
		
		panel.selectedPlaceHolderList.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) {
					/* ------------------------------------------------------- */
					removeFromSelect();
					/* ------------------------------------------------------- */
				}
				/* ====================================================== */
			}
		});
		
		
		
		/* ------------------------------------------------------- */
		// import letter template button
		/* ------------------------------------------------------- */
		panel.importDocumentButton.addActionListener(new ActionListener() {
			
			

			public void actionPerformed(ActionEvent e) {
				/* ================================================== */
				// open a filechooser
				/* ------------------------------------------------------- */
				JFileChooser chooser = MainFrame.getFileChooser();
				
				chooser.setMultiSelectionEnabled(false);
				chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				chooser.setSelectedFiles(null);
				
				chooser.setFileFilter(ControllerConfig.getExtensionFilter());
				/* ------------------------------------------------------- */
				int returnVal = chooser.showOpenDialog(NewTemplateDialog.this);
				
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					/* ------------------------------------------------------- */
					importFile = chooser.getSelectedFile();
					panel.documentLabel.setText(importFile.getName());
					/* ------------------------------------------------------- */
				}
				/* ================================================== */
			}
		});
		/* ================================================== */
	}
	
	
	/**
	 * Moves the selected placeholders from the repository list
	 * to the selectionlist
	 */
	private void moveToSelect() {
		/* ================================================== */
		// move selected items from the repository to the selection list
		/* ------------------------------------------------------- */
		Object[] selection = panel.placeHolderRepositoryList.getSelectedValues();
		/* ------------------------------------------------------- */
		if (selection == null || selection.length < 1)
			return;
		/* ------------------------------------------------------- */
		for (Object o : selection)
			selectedPlaceholders.add((LetterPlaceholder) o);
		updateRepositoryList();
		updateSelectedList();
		/* ================================================== */
	}
	
	
	/**
	 * Removes the selected placeholders from the selectionlist
	 */
	private void removeFromSelect() {
		/* ================================================== */
		// move selected items from the repository to the selection list
		/* ------------------------------------------------------- */
		Object[] selection = panel.selectedPlaceHolderList.getSelectedValues();
		/* ------------------------------------------------------- */
		if (selection == null || selection.length < 1)
			return;
		/* ------------------------------------------------------- */
		for (Object o : selection)
			selectedPlaceholders.remove(o);
		updateRepositoryList();
		updateSelectedList();
		/* ================================================== */
	}
	
	
	/**
	 * updates the selected list.
	 */
	private void updateSelectedList() {
		/* ================================================== */
		this.selectedListModel.setData(selectedPlaceholders);
		/* ================================================== */
	}
	
	
	/**
	 * Updates the repositoryList
	 */
	private void updateRepositoryList() 
	{
		String selectedCategory = (String) panel.placeHolderCategoryBox.getSelectedItem();
		
		
		if (selectedCategory == null)
			return;
		// set the not selected to the list
		repositoryListModel.setData(existingPlaceholder.get(selectedCategory));
	}
	
}
