/*******************************************************************************
 * 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.office.gui.physicianmanagement;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.HashMap;

import javax.ejb.FinderException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;

import lu.tudor.santec.gecamed.billing.gui.admin.AccountPanel;
import lu.tudor.santec.gecamed.core.ejb.session.beans.ListManagerBean;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.ListManagerInterface;
import lu.tudor.santec.gecamed.core.gui.GECAMedMessage;
import lu.tudor.santec.gecamed.core.gui.GECAMedMessageListener;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.listener.MessageListenerRegister;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialogImpl;
import lu.tudor.santec.gecamed.core.gui.widgets.LimitTextField;
import lu.tudor.santec.gecamed.core.gui.widgets.NamedComponent;
import lu.tudor.santec.gecamed.core.gui.widgets.NamedComponentVariable;
import lu.tudor.santec.gecamed.core.gui.widgets.UCMCodeField;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.core.utils.UCMCodeFormatter;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.usermanagement.ejb.entity.beans.GecamedUser;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.beans.UserAdminBean;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.UserAdminInterface;
import lu.tudor.santec.i18n.Translatrix;

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


/**
 * represents a JPanel to show/edit a physicians data
 *
 * @author Johannes Hermen johannes.hermen
 * 
 * @Version
 * <br>$Log: PhysicianDataPanel.java,v $
 * <br>Revision 1.34  2010-04-06 15:39:50  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.33  2010-03-17 16:03:47  hermen
 * <br>fixed panelchanged if users are updated
 * <br>
 * <br>Revision 1.32  2010-03-12 14:17:42  hermen
 * <br>cleanup of panel layouts and icons
 * <br>
 * <br>Revision 1.31  2009-01-14 15:04:07  hermen
 * <br>fixed ucmfacturatrion field
 * <br>
 * <br>Revision 1.30  2008-12-15 11:02:49  hermen
 * <br>added additional billing ucmcode to physician
 * <br>
 * <br>Revision 1.29  2008-12-12 13:43:24  hermen
 * <br>changed max lenght of physician phone to 20char
 * <br>
 * <br>Revision 1.28  2008-12-08 09:15:23  hermen
 * <br>reloads user-list in physician admin tab if a new user is created
 * <br>
 * <br>Revision 1.27  2008-09-25 09:43:08  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.26  2008-05-09 13:40:45  hermen
 * <br>added physician address
 * <br>
 * <br>Revision 1.25  2008-03-17 16:08:10  mack
 * <br>Changes required by moving SSNFormatter into core.utils package
 * <br>
 * <br>Revision 1.24  2008-01-15 13:08:51  hermen
 * <br>updated Javadoc and refactured code
 * <br>
 */
public class PhysicianDataDialog extends GECAMedBaseDialogImpl implements KeyListener, ItemListener {

    private static final long serialVersionUID = 1L;
    private static final String LINESPACE = "1dlu"; 
    private static final String COLUMNSPACE = "4dlu"; 

    //~ Instance fields ========================================================

    private UCMCodeField ucmField;
    private UCMCodeField ucmFacturation;
    private JTextField firstName;
    private JTextField lastName;
    private String[] titleArray;
	private JComboBox<String> titel;
	private GecamedUser[] userArray;
	private JComboBox<GecamedUser> user;
	private JTextArea speciality;
	private JTextField email;
	private JTextField phone;
	private JTextField fax;
	private JTextField gsm;
	
	private boolean listenersActivated = false;
	private Integer userID;
	private UserAdminInterface usermanager;
	private AccountPanel accountPanel;
	private JButton colorChooser;
	private PhysicianAddressPanel addressPanel;
	private JPanel mainPanel;

    //~ Constructors ===========================================================
    /**
     * builds a new PatientInfo to show/edit general Patient Data
     */
    public PhysicianDataDialog() {
    	
    	super(MainFrame.getInstance(), Translatrix.getTranslationString("office.physicianmanagement"), OK_CANCEL_BUTTON_MODE);
    	
    	this.buildPanel();
    	
    	this.addMainPanel(mainPanel);
    	
    	this.setEditable(true);

    	this.setSize(1100, 450);
    }

    //~ Methods ================================================================
    /**
     * saves the Values of all fields to the passed StaffValue object
     *
     * @param physician the StaffValue object to store the values in
     */
    public Physician getData (Physician physician)
    {
    	if (physician == null) {
    		physician = new Physician();
    	}
    	
        // row 1
    	physician.setTitle((String) this.titel.getSelectedItem());
        physician.setFirstName(this.firstName.getText());
        physician.setName(this.lastName.getText());
        try {
        	userID = ((GecamedUser) this.user.getSelectedItem()).getId();		
		} catch (Exception e) {
			userID = null;
		}
        physician.setUserId(userID);

        // row 2
        physician.setUcmCode((String) this.ucmField.getText());
        if (physician.getUcmCode() == null)
        	physician.setUcmCode(Physician.UCM_DEFAULT);
        
        physician.setUcmFacturation((String) this.ucmFacturation.getText());
        if (Physician.UCM_DEFAULT.equals(physician.getUcmFacturation())) {
            physician.setUcmFacturation(null);
        } 
        
        physician.setSpeciality(this.speciality.getText());
        physician.setEmail(this.email.getText());
        physician.setPhoneExtension(this.phone.getText());
        physician.setFax(this.fax.getText());
        physician.setGsm(this.gsm.getText());
        
        physician.setColor(this.colorChooser.getBackground().getRGB());
        
        addressPanel.getData(physician);
        
        return physician;
    }

    /**
     * fills the fields of the panel with data from the passed StaffValue
     * object.
     *
     * @param physician the StaffValue object to load the values from
     */
    public void setPhysician(Physician  physician)
    {
//    	listenersActivated = false;
        // row 1
    	if (physician.getTitle() != null) {
    		this.titel.setSelectedItem(physician.getTitle());
    	} else {
    		try {
    			this.titel.setSelectedIndex(0);
			} catch (Exception e) {
			}
    	}
        this.firstName.setText(physician.getFirstName());
        this.lastName.setText(physician.getName());
        
		try {
        	GecamedUser user = usermanager.getUser(physician.getUserId());
    		this.user.setSelectedItem(user);
		} catch (Exception e) {
    		this.user.setSelectedIndex(0);
    	}
        
        this.ucmField.setValue(physician.getUcmCode());
        this.speciality.setText(physician.getSpeciality());
        this.email.setText(physician.getEmail());
        this.phone.setText(physician.getPhoneExtension());
        this.fax.setText(physician.getFax());
        this.gsm.setText(physician.getGsm());
        
        if (physician.getUcmFacturation() != null) {
            this.ucmFacturation.setValue(physician.getUcmFacturation());            
        } else {
            this.ucmFacturation.setValue(Physician.UCM_DEFAULT);
        }
        
        try {
        	this.colorChooser.setBackground(new Color(physician.getColor()));			
		} catch (Exception e) {
			this.colorChooser.setBackground(new JButton().getBackground());
		}
        
        this.addressPanel.setPhysician(physician);
        this.accountPanel.setHolder(physician);
        
//        listenersActivated = true;
    }

    /**
     * adds the components to the panel
     */
    private void buildPanel() {
	
    	mainPanel = new JPanel();
    	mainPanel.setOpaque(false);
    	
//    	setHeader(Translatrix.getTranslationString("office.physicianmanagement"));
	
        initComponents();
        // build Layout
        String line = ""; 
        for (int i = 1; i <= 6; i++) {
            line = line + "50dlu:grow, " + COLUMNSPACE + ", "; 
        }
        FormLayout layout = new FormLayout(line,"pref, " + LINESPACE + ", top:pref, " + LINESPACE + ",pref, "  + LINESPACE + ",pref:grow, " + LINESPACE + ",pref, " + LINESPACE +", 80dlu"); 
        this.mainPanel.setLayout(layout);
        CellConstraints cc = new CellConstraints();

        // add Labels (line 1)
        this.mainPanel.add(new NamedComponent(Translatrix.getTranslationString("phy.titel"), this.titel),cc.xyw(1, 1, 1));
        this.mainPanel.add(new NamedComponent(Translatrix.getTranslationString("phy.firstName"), this.firstName),cc.xyw(3, 1, 3));
        this.mainPanel.add(new NamedComponent(Translatrix.getTranslationString("phy.lastName"), this.lastName), cc.xyw(7, 1, 1)); 
        this.mainPanel.add(new NamedComponent(Translatrix.getTranslationString("phy.ucm"), this.ucmField), cc.xyw(9, 1, 1));
        this.mainPanel.add(new NamedComponent(Translatrix.getTranslationString("phy.user"), this.user), cc.xyw(11, 1, 1)); 
        
        // add Labels (line 2)
        this.mainPanel.add(new NamedComponentVariable(Translatrix.getTranslationString("phy.speciality"), new JScrollPane(speciality)), cc.xywh(1, 3, 5, 5)); 
        this.mainPanel.add(new NamedComponent(Translatrix.getTranslationString("phy.email"), this.email), cc.xyw(7, 3, 1));
        this.mainPanel.add(new NamedComponent(Translatrix.getTranslationString("phy.phone"), this.phone), cc.xyw(9, 3, 1));
        this.mainPanel.add(new NamedComponent(Translatrix.getTranslationString("phy.fax"), this.fax), cc.xyw(11, 3, 1));
        this.mainPanel.add(new NamedComponent(Translatrix.getTranslationString("phy.gsm"), this.gsm), cc.xyw(11, 5, 1));
        
        this.mainPanel.add(this.colorChooser, cc.xyw(7, 5, 1)); 
        this.mainPanel.add(new NamedComponent(Translatrix.getTranslationString("phy.ucmfact"), this.ucmFacturation), cc.xyw(9, 5, 1));
        this.mainPanel.add(addressPanel, cc.xyw(1,9,11));
        this.mainPanel.add(accountPanel, cc.xyw(1,11,11));
        
    }

    /**
     * initializes the Components
     */
	private void initComponents() {
	    // Get the type manager
    	try {
    	    ListManagerInterface manager = (ListManagerInterface) ManagerFactory.getRemote(ListManagerBean.class);
    	    titleArray = manager.getDrTitles();
    
    	    usermanager = (UserAdminInterface) ManagerFactory.getRemote(UserAdminBean.class);
    	    ArrayList<GecamedUser> userlist = new ArrayList<GecamedUser>(usermanager.getUserList());
    	    userlist.add(0, new GecamedUser(Translatrix.getTranslationString("phy.selectUser")));
    	    userArray = userlist.toArray(new GecamedUser[0]);
    	} catch (Exception e) {
    	    MainFrame.reportServerError(e);
    	}
    	
    	// reload users
		MessageListenerRegister.addGECAMedMessageListener(new GECAMedMessageListener() {
			public void handleGECAMedMessage(GECAMedMessage message) {
				if (message.getMessage().equals(MessageListenerRegister.MESSAGE_USER_CHANGED)) {
					listenersActivated = false;
					try {
						ArrayList<GecamedUser> userlist = new ArrayList<GecamedUser>(usermanager.getUserList());
						user.removeAllItems();
						user.addItem(new GecamedUser(Translatrix.getTranslationString("phy.selectUser")));
						for (GecamedUser gecamedUser : userlist) {
							user.addItem(gecamedUser);
						}
					} catch (FinderException e) {
						e.printStackTrace();
					}
					listenersActivated = true;
				}
			}
		});
    	
            
		this.titel = new JComboBox<String>(this.titleArray);
		this.titel.addItemListener(this);
		try {
			this.titel.setSelectedIndex(1);
		} catch (Exception e) {
		}
		this.firstName = new LimitTextField(30);
		this.firstName.addKeyListener(this);
		this.lastName = new LimitTextField(30);
		this.lastName.addKeyListener(this);

		this.user = new JComboBox<GecamedUser>(userArray);
		this.user.addItemListener(this);

		this.ucmField = new UCMCodeField(new UCMCodeFormatter());
		this.ucmField.addKeyListener(this);

		this.ucmFacturation = new UCMCodeField(new UCMCodeFormatter());
		this.ucmFacturation.addKeyListener(this);

		this.speciality = new JTextArea(2, 40);
		this.speciality.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
		this.speciality.addKeyListener(this);

		this.colorChooser = new JButton(Translatrix.getTranslationString("phy.chooseColor"));
		this.colorChooser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Component comp = (Component) e.getSource();
				Color oldColor = comp.getBackground();
				Color newColor = JColorChooser.showDialog(MainFrame.getInstance(), Translatrix.getTranslationString("phy.chooseColor"), comp.getBackground());
				if (oldColor != newColor) {
					comp.setBackground(newColor);
					setUnsavedChanges(true);
				}
			}
		});
            
		this.email = new LimitTextField(90);
		this.email.addKeyListener(this);

		this.phone = new LimitTextField(20);
		this.phone.addKeyListener(this);

		this.fax = new LimitTextField(20);
		this.fax.addKeyListener(this);

		this.gsm = new LimitTextField(20);
		this.gsm.addKeyListener(this);

		this.accountPanel = new AccountPanel();

		this.addressPanel = new PhysicianAddressPanel(this);
        
    }

	public void keyTyped(KeyEvent e) {}
	public void keyPressed(KeyEvent e) {}
	public void keyReleased(KeyEvent e) {
		this.setUnsavedChanges(true);
	}

	public void itemStateChanged(ItemEvent e) {
		if (listenersActivated ) {
			this.setUnsavedChanges(true);
		}
	}

	/**
	 * enables/disables this panel and all subpanels
	 * @param enabled
	 */
	public void setEditable(boolean enabled) {
		this.ucmField.setEditable(enabled);
		this.ucmFacturation.setEditable(enabled);
		this.firstName.setEditable(enabled);
		this.lastName.setEditable(enabled);
		this.titel.setEnabled(enabled);
		this.user.setEnabled(enabled);
		this.speciality.setEditable(enabled);
		this.email.setEditable(enabled);
		this.colorChooser.setEnabled(enabled);
		this.phone.setEditable(enabled);
		this.fax.setEditable(enabled);
		this.gsm.setEditable(enabled);
		this.accountPanel.setEditable(enabled);
	}
	
	void setUnsavedChanges(boolean b) {
		// TODO Auto-generated method stub
	}

}
