/*******************************************************************************
 * 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.sitemanagement;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import lu.tudor.santec.gecamed.billing.gui.TextWrappingCellRenderer;
import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedLists;
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.gui.widgets.HeaderedPanel;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Site;
import lu.tudor.santec.gecamed.office.ejb.session.beans.OfficeManagerBean;
import lu.tudor.santec.gecamed.office.ejb.session.interfaces.OfficeManagerInterface;
import lu.tudor.santec.gecamed.office.gui.PhysicianComboBoxRenderer;
import lu.tudor.santec.gecamed.office.gui.officemanagement.OfficeManagementPanel;
import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.widgets.gui.ButtonFactory;

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

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

/**
 *  JPanel with a table of all sites and options to delete and create new ones.
 *
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @version
 * <br>$Log: SiteManagementPanel.java,v $
 * <br>Revision 1.8  2013-12-27 18:09:26  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.7  2013-07-15 06:18:37  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.6  2010-03-12 14:54:14  hermen
 * <br>cleanup of panel layouts and icons
 * <br>
 * <br>Revision 1.5  2010-03-12 14:17:42  hermen
 * <br>cleanup of panel layouts and icons
 * <br>
 * <br>Revision 1.4  2009-02-27 15:25:56  hermen
 * <br>added button to create an empty incident for a patient visit
 * <br>
 * <br>Revision 1.3  2009-02-25 13:26:09  hermen
 * <br>added siteID to incidents and invoices
 * <br>
 * <br>Revision 1.2  2009-02-11 14:14:34  hermen
 * <br>added management of sites to the office admin tab
 * <br>
 * <br>Revision 1.1  2009-02-11 14:05:53  hermen
 * <br>added management of sites to the office admin tab
 * <br>
 * <br>
 *
 */
public class SiteManagementPanel extends HeaderedPanel {

	private static final long serialVersionUID = 1L;

	private static final String SITE = "site.png";

	private static Logger logger = Logger
			.getLogger(SiteManagementPanel.class.getName());
	
	private JTable siteTable;
	
        private JButton newButton;
        private JButton deleteButton;
        private JButton editButton;

	private SiteTableModel tableModel;

	private OfficeManagerInterface manager;

	private boolean notBuild = true;

	private boolean isEnabled;

	private SiteEditDialog siteEditDialog;

	private OfficeManagementPanel officeManagementPanel; 

	public SiteManagementPanel(OfficeManagementPanel officeManagementPanel) {
		this.setOpaque(true);
		this.officeManagementPanel = officeManagementPanel;
		this.setBackground(GECAMedColors.c_GECAMedBackground);
		Translatrix.addBundle("lu.tudor.santec.gecamed.office.gui.resources.WidgetResources");

		if (notBuild) {
			buildPanel();
			notBuild = false;
		}
		loadSites();
	}
			
	/**
         * adds the components to the panel
         */
        private void buildPanel()
        {
            
            setHeader(Translatrix.getTranslationString("office.sitemanagement"));
            
            initComponents();
            // build Layout
            FormLayout layout = new FormLayout("100dlu:grow, pref","top:120dlu:grow"); 
            this.setLayout(layout);
            CellConstraints cc = new CellConstraints();
            JScrollPane pane = new JScrollPane(this.siteTable); 
            pane.setBackground(GECAMedColors.c_ScrollPaneBackground);
            pane.getViewport().setOpaque(false);
            this.add(pane, cc.xy(1, 1));
            
            JPanel bb = new JPanel(new FormLayout("pref", "pref,1dlu,pref,1dlu,pref,1dlu,pref:grow"));
            bb.setOpaque(false);
            bb.add(this.editButton, cc.xy(1, 1));
            bb.add(this.newButton, cc.xy(1, 3));
            bb.add(this.deleteButton, cc.xy(1, 5));
            this.add(bb, cc.xy(2, 1));
            
        }

    /**
     * initializes the Components
     */
    private void initComponents()
    {
	// Get the type manager
	this.manager = (OfficeManagerInterface) ManagerFactory.getRemote(OfficeManagerBean.class);
	  
	this.siteEditDialog = new SiteEditDialog();
		    
    	this.tableModel = new SiteTableModel();
    	this.siteTable = new JTable(this.tableModel);
    	this.siteTable.setGridColor(this.siteTable.getBackground());
    	
    	this.siteTable.getColumnModel().getColumn(0).setMaxWidth(20);
    	this.siteTable.getColumnModel().getColumn(1).setMaxWidth(30);
    	this.siteTable.getColumnModel().getColumn(1).setMinWidth(80);
    	this.siteTable.getColumnModel().getColumn(2).setCellRenderer(new TextWrappingCellRenderer());
    	this.siteTable.getColumnModel().getColumn(3).setCellRenderer(new TextWrappingCellRenderer());
    	this.siteTable.getColumnModel().getColumn(4).setCellRenderer(new TextWrappingCellRenderer());

    	this.siteTable.setRowHeight(20);
    	this.siteTable.addMouseListener(
		new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				/* ============================================= */
				// doubleclick --> open
				if (e.getClickCount() >= 2) {
					// get the current row
					int row = siteTable.rowAtPoint(e.getPoint());
					siteTable.setRowSelectionInterval(row, row);
					try {
					    Site site = tableModel.getSite(row);
					    editSite(site);
					} catch (Exception ee) {
					    MainFrame.reportServerError(ee);
					}
				} 
				/* ============================================= */
			}
		});
    	
    	this.editButton = ButtonFactory.createNarrowButton(GECAMedModule.getSmallIcon(GECAMedModule.EDIT));
    	this.editButton.setToolTipText(Translatrix.getTranslationString("core.edit"));
	this.editButton.setHorizontalAlignment(JButton.LEFT);
	this.editButton.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		/* ============================================= */
			// get the current row
			int row = siteTable.getSelectedRow();
			if (row < 0)
			    return;
			try {
			    Site site = tableModel.getSite(row);
			    editSite(site);
			} catch (Exception ee) {
			    MainFrame.reportServerError(ee);
			}
		/* ============================================= */
	    }
	});
	
    	this.newButton = ButtonFactory.createNarrowButton(GECAMedModule.getSmallIcon(GECAMedIconNames.ADD_LINE));
    	this.newButton.setToolTipText(Translatrix.getTranslationString("core.add"));
    	this.newButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			    editSite(new Site());
			}
    	});
    	
    	this.deleteButton = ButtonFactory.createNarrowButton(GECAMedModule.getSmallIcon(GECAMedIconNames.REMOVE_LINE));
    	this.deleteButton.setToolTipText(Translatrix.getTranslationString("core.delete"));
    	this.deleteButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
				    int row = siteTable.getSelectedRow();
				    if (row < 0)
					return;
				    Site currentSite = tableModel.getSite(row);
					if (currentSite.getId() != null) {
						manager.deleteSite(currentSite.getId());
						tableModel.getData().remove(currentSite);
					}
				} catch (Exception e2) {
					logger.log(Level.WARN, "Error deleting site", e2);
					JOptionPane.showMessageDialog(MainFrame.getInstance(),
						    "Site could not be deleted,\nIt might still be references in incidents",
						    "Error deleting site",
						    JOptionPane.ERROR_MESSAGE);
				}
				
				tableModel.fireTableDataChanged();
				updateSiteList();
				
				try {
					siteTable.setRowSelectionInterval(0,0);
				} catch (Exception ee) {
				}
			}
    	});
    	
		this.newButton.setHorizontalTextPosition(JLabel.RIGHT);
		this.newButton.setHorizontalAlignment(JLabel.LEFT);
		this.deleteButton.setHorizontalTextPosition(JLabel.RIGHT);
		this.deleteButton.setHorizontalAlignment(JLabel.LEFT);
    	
    }

    protected void editSite(Site site) {
    	this.siteEditDialog.editSite(site);
    	site = this.siteEditDialog.getSite();
    	if (site == null)
    	    return;
    	
    	if (site.getName() != null && ! site.getName().equals("") && site.getSiteAddress() != null) {
       		try {
       		    	site.setOffice_id(officeManagementPanel.currentOffice.getId());
       			site = manager.saveSite(site);
       		} catch (Exception e1) {
       			logger.log(Level.WARN, "saving site failed");
       		}
       		updateSiteList();
       		loadSites();
    	}
    }


	private void updateSiteList ()
	{
		/* ====================================================== */
		GECAMedLists.resetListAndNotifyListener(Site.class);
		
//		Site[] sites;
//		try
//		{
//			sites = (Site[]) ((OfficeManagerInterface) ManagerFactory.getRemote(OfficeManagerBean.class))
//					.getSites().toArray(new Site[0]);
//			GECAMedLists.storeList(Site.class, sites);
//		}
//		catch (Exception e)
//		{
//			e.printStackTrace();
//		}
		// save sites in global hashmap
		/* ====================================================== */
	}
    
		
	public void loadSites() {
		try {
        		Collection<Site> l = manager.getSites();
        		if (l == null) {
        			l = new ArrayList<Site>();
        		}
        		this.tableModel.setData(l);
			this.siteTable.setRowSelectionInterval(0,0);
		} catch (Exception e) {
		}
	}
		
	/**
	 * 
	 * 
	 *
	 * @author Johannes Hermen johannes.hermen(at)tudor.lu
	 *
	 * @version
	 * <br>$Log: SiteManagementPanel.java,v $
	 * <br>Revision 1.8  2013-12-27 18:09:26  donak
	 * <br>Cleanup of imports
	 * <br>
	 * <br>Revision 1.7  2013-07-15 06:18:37  ferring
	 * <br>logging changed
	 * <br>
	 * <br>Revision 1.6  2010-03-12 14:54:14  hermen
	 * <br>cleanup of panel layouts and icons
	 * <br>
	 * <br>Revision 1.5  2010-03-12 14:17:42  hermen
	 * <br>cleanup of panel layouts and icons
	 * <br>
	 * <br>Revision 1.4  2009-02-27 15:25:56  hermen
	 * <br>added button to create an empty incident for a patient visit
	 * <br>
	 * <br>Revision 1.3  2009-02-25 13:26:09  hermen
	 * <br>added siteID to incidents and invoices
	 * <br>
	 * <br>Revision 1.2  2009-02-11 14:14:34  hermen
	 * <br>added management of sites to the office admin tab
	 * <br>
	 * <br>Revision 1.1  2009-02-11 14:05:53  hermen
	 * <br>added management of sites to the office admin tab
	 * <br>
	 *
	 */
	class SiteTableModel extends AbstractTableModel {

		private static final long serialVersionUID = 1L;
		private ArrayList<Site> data;
		private ImageIcon siteIcon = IconFetcher.getMiniIcon(PhysicianComboBoxRenderer.class, SiteManagementPanel.SITE);
		
		private String[] columnName = {
				"",
				"ID",
				Translatrix.getTranslationString("core.site"),
				Translatrix.getTranslationString("pm.address"),
				Translatrix.getTranslationString("pm.phoneInfo")
		};

		private Class[] columnsClasses = {
		    	ImageIcon.class,
		    	Integer.class,
				String.class,
				String.class,
				String.class
		};
		
		@SuppressWarnings("unchecked")
		public void setData(Collection<Site> data) {
			if (data != null) {
				this.data = new ArrayList(data);
			} else {
				this.data = null;
			}
			this.fireTableDataChanged();
		}
		
		public ArrayList<Site> getData() {
			return data;
		}
		
		public String getColumnName(int column) {
			return columnName[column];
		}

		public int getRowCount() {
			try {
				return data.size();
			} catch (Exception e) {
				return 0;
			}
		}

		public int getColumnCount() {
			return columnsClasses.length;
		}
		
		public Class<?> getColumnClass(int column) {
			return columnsClasses[column];
		}

		public Object getValueAt(int rowIndex, int columnIndex) {
			Site site = data.get(rowIndex);
			try {
				switch (columnIndex) {
				case 0:
				    return siteIcon;
				case 1:
			    	return site.getId();
				case 2:
					return site.getName();
				case 3:
					return site.getSiteAddress() + "";
				case 4:
					return "Tel: " + site.getPhone() + " Fax: " + site.getFax();
				default:
					return "";
				}
			} catch (Exception e) {
				return "";
			}
		}

		public boolean isCellEditable(int rowIndex, int columnIndex) {
			return false;
		}

		public Site getSite(int row) {
			try {
				return data.get(row);	
			} catch (Exception e) {
				return null;
			}
			
		}
		
	}
    
	public void preparetoShowup() {
	}
	
	public void enablePanel(boolean b) {
		this.isEnabled = b;
		this.newButton.setEnabled(b);
		this.deleteButton.setEnabled(b);
		this.editButton.setEnabled(b);
	}
	
}
