/*******************************************************************************
 * 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.billing.gui.templates;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.JButton;

import lu.tudor.santec.gecamed.billing.ejb.entity.beans.InvoiceTemplate;
import lu.tudor.santec.gecamed.billing.ejb.session.beans.InvoiceTemplateBean;
import lu.tudor.santec.gecamed.billing.ejb.session.interfaces.InvoiceTemplateInterface;
import lu.tudor.santec.gecamed.billing.gui.BillingModule;
import lu.tudor.santec.gecamed.billing.utils.BillingUserSettings;
import lu.tudor.santec.gecamed.core.gui.GECAMedFonts;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
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.Patient;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.gecamed.patient.gui.incident.AccidentRelationDialog;
import lu.tudor.santec.gecamed.usermanagement.gui.settings.UserSettingsPlugin;

import org.apache.log4j.Logger;

public class TemplateManager implements ActionListener {

	private static Logger m_Logger = Logger.getLogger ("lu.tudor.santec.gecamed.billing.gui.templates");
	private static TemplateManager templateManager;
	private InvoiceTemplateInterface templateInterface;
	private LinkedHashMap<String, InvoiceTemplate> templateMap = new LinkedHashMap<String, InvoiceTemplate>();

	private static int[] hotkeys = { KeyEvent.VK_NUMPAD0,
									 KeyEvent.VK_NUMPAD1,
									 KeyEvent.VK_NUMPAD2,
									 KeyEvent.VK_NUMPAD3,
									 KeyEvent.VK_NUMPAD4,
									 KeyEvent.VK_NUMPAD5,
									 KeyEvent.VK_NUMPAD6,
									 KeyEvent.VK_NUMPAD7,
									 KeyEvent.VK_NUMPAD8,
									 KeyEvent.VK_NUMPAD9 };

	
	public TemplateManager() {

		this.getAllTemplates();
		templateManager = this;

	}

	private void getAllTemplates () {
		Integer userId = MainFrame.getCurrentUserId();
		Integer templateUserId;
		
		
		try {
			templateInterface = (InvoiceTemplateInterface) ManagerFactory.getRemote(InvoiceTemplateBean.class);
//			InitialContext l_Context = new InitialContext();
// 			templateInterface = (InvoiceTemplateInterface) l_Context.lookup("InvoiceTemplateBean/remote");
// 			l_Context.close();
 			}
 		catch (Exception p_Exception)
 			{
 			m_Logger.warn(p_Exception.getLocalizedMessage());
 			}

 		try {
			Collection<InvoiceTemplate> templates = templateInterface.getAllTemplates();
			if (templates != null)
				{
				for (Iterator<InvoiceTemplate> iter = templates.iterator(); iter.hasNext();) {
					InvoiceTemplate template = (InvoiceTemplate) iter.next();
					templateUserId = template.getUserId();
					if (templateUserId == null || templateUserId.equals(userId))
						templateMap.put(template.getShortcut(),template);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	
	public Vector<AbstractButton> getTemplateButtons(boolean forceReload) {
		Vector<AbstractButton> v = new Vector<AbstractButton>();
		int					   i = 0;
		Integer				   maxButtons;
		
		// if user has no rights to create invoices, show no template buttons
		if ( ! BillingModule.userHasPermission (BillingModule.c_BillingModule, BillingModule.c_createInvoices))
			return v;
		
		maxButtons = (Integer) BillingModule.getUserSetting(BillingUserSettings.c_TemplateButtonsSetting);
		if (maxButtons == null) maxButtons = Integer.valueOf(0);
		
		if (forceReload) 
			{	
			templateMap = new LinkedHashMap<String, InvoiceTemplate>();
			this.getAllTemplates();
			}
		
		for (Iterator<InvoiceTemplate> iter = templateMap.values().iterator(); iter.hasNext() && (i < maxButtons.intValue());i++) {
				InvoiceTemplate  template = (InvoiceTemplate) iter.next();
				JButton button = new JButton(template.getShortcut());
				button.setActionCommand(template.getShortcut());
				button.setToolTipText(template.getLabel());
				button.addActionListener(this);
				button.setFont(GECAMedFonts.BUTTON_FONT);
				if (i < hotkeys.length && PatientManagerModule.getUseMnemonics()) {
					button.setMnemonic(hotkeys[i]);
					button.setToolTipText(template.getLabel() + " [ALT+NUMPAD"+i+"]");
				}
				v.add(button);
		}
		return v;
	}


	public void actionPerformed(ActionEvent e) {


		Patient l_Patient = GECAMedModule.getCurrentPatient();
		InvoiceTemplate t = templateMap.get(e.getActionCommand());
		
		MainFrame.getInstance().selectModule(BillingModule.MODULE_NAME);
				
		BillingModule.getInstance().newInvoice(t);
		
		// Ask for an accident
		// show AccidentRelationDialog
		AccidentRelationDialog rd = AccidentRelationDialog.getInstance();
		List<Incident> acc = PatientManagerModule.getPatientAccidents(l_Patient.getId());
		if (
				acc != null
				&& acc.size() > 0
				&& ! AccidentRelationDialog.NOT_SHOW_AGAIN
				&& ((Boolean)MainFrame.getInstance().userSettings.getValue(UserSettingsPlugin.SHOW_ACCIDENT_RELATION_ENABLED))
		) {
			rd.showDialog(acc.get(0), acc,false, AccidentRelationDialog.TYPE_INVOICE);
			/* ------------------------------------------------------- */
			Incident ret = rd.getSelectedAccident();
			if (ret != null) {
				/* ------------------------------------------------------- */
				// set the accident data to the invoice
				BillingModule.getInstance().setAccident(ret.getAccidentNr(), ret.getAccidentDate());
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
		}
			
	}

	public static TemplateManager getInstance(){
		if (templateManager == null) {
			templateManager = new TemplateManager();
		}
		return templateManager;
	}

}
