package lu.tudor.santec.gecamed.importexport.gui.importer;
//package lu.tudor.santec.gecamed.importexport;
//
//import java.awt.BorderLayout;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.io.File;
//import java.io.FileInputStream;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.HashSet;
//import java.util.Properties;
//import java.util.Vector;
//
//import javax.naming.InitialContext;
//import javax.security.auth.callback.CallbackHandler;
//import javax.security.auth.login.LoginContext;
//import javax.swing.JButton;
//import javax.swing.JFileChooser;
//import javax.swing.JPanel;
//import javax.swing.JScrollPane;
//import javax.swing.JTextArea;
//
//import lu.tudor.santec.gecamed.address.ejb.entity.beans.Country;
//import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Account;
//import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Settlement;
//import lu.tudor.santec.gecamed.billing.ejb.session.beans.SettlementBean;
//import lu.tudor.santec.gecamed.billing.ejb.session.interfaces.SettlementInterface;
//import lu.tudor.santec.gecamed.core.ejb.entity.beans.GECAMedLocale;
//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.JaasJbossConfiguration;
//import lu.tudor.santec.gecamed.core.gui.LoginCallbackHandler;
//import lu.tudor.santec.gecamed.core.gui.MainFrame;
//import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialog;
//import lu.tudor.santec.gecamed.core.gui.widgets.PasswordChangeDialog;
//import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
//import lu.tudor.santec.gecamed.importexport.utils.CSVFileReader;
//import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
//import lu.tudor.santec.gecamed.office.ejb.entity.beans.PhysicianAddress;
//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.usermanagement.ejb.entity.beans.GecamedUser;
//import lu.tudor.santec.gecamed.usermanagement.ejb.entity.beans.Role;
//import lu.tudor.santec.gecamed.usermanagement.ejb.session.beans.UserAdminBean;
//import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.UserAdminInterface;
//
//import org.apache.log4j.Level;
//import org.apache.log4j.Logger;
//
///**
// * Importer to read and create Users and Physicians from a CSV file Used to
// * import the physicians for the Mais. Medicale
// * 
// * 
// * @author Johannes Hermen johannes.hermen(at)tudor.lu
// * 
// * @version <br>
// *          $Log: PhysicianCVSImport.java,v $
// *          Revision 1.6  2013-12-27 18:09:25  donak
// *          Cleanup of imports
// *
// *          Revision 1.5  2013-07-15 06:18:36  ferring
// *          logging changed
// *
// *          Revision 1.4  2012-02-07 10:40:00  ferring
// *          printStackTraces replaced by logging
// * <br>
// *          Revision 1.3 2008-11-28 09:30:21 hermen <br>
// *          *** empty log message *** <br>
// * <br>
// *          Revision 1.2 2008-11-27 09:43:17 hermen <br>
// *          mporter to read and create Users and Physicians from a CSV file <br>
// *          Used to import the physicians for the Mais. Medicale <br>
// * <br>
// *          Revision 1.1 2008-11-26 14:07:05 hermen <br>
// *          mporter to read and create Users and Physicians from a CSV file <br>
// *          Used to import the physicians for the Mais. Medicale <br>
// * 
// */
//public class PhysicianCVSImport extends GECAMedBaseDialog implements ActionListener
//{
//	/** the logger Object for this class */
//	private static Logger			logger				= Logger.getLogger(PhysicianCVSImport.class.getName());
//	
//	private static final long		serialVersionUID	= 1L;
//	
//	public static final int			Number				= 0;
//	
//	public static final int			Title				= 1;
//	
//	public static final int			Name				= 2;
//	
//	public static final int			Firstname			= 3;
//	
//	public static final int			UCMCode				= 4;
//	
//	public static final int			Tel					= 5;
//	
//	public static final int			Fax					= 6;
//	
//	public static final int			Email				= 7;
//	
//	public static final int			Speciality			= 8;
//	
//	public static final int			Zipcode				= 9;
//	
//	public static final int			Locality			= 10;
//	
//	public static final int			Streetname			= 11;
//	
//	public static final int			StreetNr			= 12;
//	
//	public static final int			Language			= 13;
//	
//	public static final int			Bankname			= 14;
//	
//	public static final int			BICCode				= 15;
//	
//	public static final int			IBANCode			= 16;
//	
//	private UserAdminInterface		userAdmin;
//	
//	private OfficeManagerInterface	officeManager;
//	
//	private SettlementInterface		settlementInterface;
//	
//	private ListManagerInterface	listManagerInterface;
//	
//	private JTextArea				textArea;
//	
//	private JButton					fileButton;
//	
//	private JFileChooser			jfileChooser		= new JFileChooser();
//	
//	private File					file;
//	
//	private static final String		INIT_STRING			= "FOR INTERNAL USE ONLY\n" + "Only use this Dialog if you know what you are doing!!!!!";
//	
//	
//	public PhysicianCVSImport()
//	{
//		super("Physician Import", true, true, false);
//		
//		JPanel content = new JPanel(new BorderLayout());
//		
//		fileButton = new JButton("choose File");
//		fileButton.addActionListener(this);
//		content.add(fileButton, BorderLayout.NORTH);
//		
//		textArea = new JTextArea(INIT_STRING);
//		content.add(new JScrollPane(textArea), BorderLayout.CENTER);
//		
//		this.addMainPanel(content);
//		
//		this.okButton.addActionListener(this);
//		this.cancelButton.addActionListener(this);
//		
//		this.setSize(700, 700);
//		if (MainFrame.getInstance() != null)
//			this.setLocationRelativeTo(MainFrame.getInstance());
//		this.setVisible(true);
//	}
//	
//	
//	public void runImport(File f)
//	{
//		try
//		{
//			
//			this.userAdmin = (UserAdminInterface) ManagerFactory.getRemote(UserAdminBean.class);
//			this.officeManager = (OfficeManagerInterface) ManagerFactory.getRemote(OfficeManagerBean.class);
//			this.settlementInterface = (SettlementInterface) ManagerFactory.getRemote(SettlementBean.class);
//			this.listManagerInterface = (ListManagerInterface) ManagerFactory.getRemote(ListManagerBean.class);
//			
//			Vector<String> rolesNames = new Vector<String>();
//			rolesNames.add("PatientModule.physician");
//			rolesNames.add("BillingModule.Editing");
//			rolesNames.add("BillingModule.Viewing");
//			rolesNames.add("LaboModule.Downloading");
//			rolesNames.add("LaboModule.Viewing");
//			
//			// fetch needed roles
//			HashSet<Role> roles2Add = new HashSet<Role>();
//			ArrayList<Role> allRoles = new ArrayList<Role>(userAdmin.getRoles());
//			for (Role role : allRoles)
//			{
//				if (rolesNames.contains(role.getName()))
//				{
//					roles2Add.add(role);
//				}
//			}
//			
//			// fetch needed locale
//			GECAMedLocale locale = null;
//			GECAMedLocale[] locales = listManagerInterface.getGECAMedLocales();
//			for (int i = 0; i < locales.length; i++)
//			{
//				if (locales[i].getLanguage().equals(GECAMedLocale.FRENCH))
//				{
//					locale = locales[i];
//					break;
//				}
//			}
//			
//			Vector<String> createdUsers = new Vector<String>();
//			
//			CSVFileReader reader = new CSVFileReader(f.getAbsolutePath(), ',', '\'');
//			Vector<String> fields = null;
//			fields = reader.readFields();
//			while (fields != null && fields.size() >= 0)
//			{
//				// handle the line
//				try
//				{
//					StringBuffer sb = new StringBuffer();
//					
//					try
//					{
//						write("Parsing Line: " + Integer.parseInt(fields.get(Number)));
//					}
//					catch (Exception e)
//					{
//						// skip this line
//						fields = reader.readFields();
//						continue;
//					}
//					
//					// create a user
//					GecamedUser user = new GecamedUser();
//					user.setName(fields.get(Firstname) + " " + fields.get(Name));
//					
//					String userName = (fields.get(Name).toLowerCase().replaceAll("[\\W]", ""));
//					if (userName.length() > 10)
//						userName.substring(0, 10);
//					userName = userName + fields.get(Firstname).substring(0, 1).toLowerCase();
//					
//					user.setLogin(userName);
//					sb.append("'" + user.getName() + "',");
//					sb.append("'" + user.getLogin() + "',");
//					String password = generateCode(8);
//					sb.append("'" + password + "'");
//					
//					user.setPasswordhash(PasswordChangeDialog.getEncodedHash(password));
//					user.setLanguage(lu.tudor.santec.gecamed.core.ejb.entity.beans.Language.FRENCH);
//					user.setLastModification(new Date());
//					user.setModifiedBy(1);
//					user.setRoles(roles2Add);
//					
//					user.setGecamedLocale(locale);
//					
//					// check if user allready exists, then skip
//					try
//					{
//						GecamedUser u = userAdmin.getUser(user.getLogin());
//						if (u != null)
//						{
//							write("User allready exits: " + user.getLogin());
//							fields = reader.readFields();
//							continue;
//						}
//					}
//					catch (Exception e)
//					{
//					}
//					
//					write("creating user: " + user);
//					user = userAdmin.saveUser(user);
//					
//					// create an physician
//					Physician phy = new Physician();
//					phy.setName(fields.get(Name));
//					phy.setFirstName(fields.get(Firstname));
//					phy.setTitle(fields.get(Title));
//					phy.setUcmCode(fields.get(UCMCode));
//					phy.setPhoneExtension(fields.get(Tel));
//					phy.setFax(fields.get(Fax));
//					phy.setEmail(fields.get(Email));
//					phy.setSpeciality(fields.get(Speciality));
//					phy.setUserId(user.getId());
//					
//					// create address
//					PhysicianAddress pa = new PhysicianAddress();
//					pa.setZip(fields.get(Zipcode));
//					pa.setLocality(fields.get(Locality));
//					pa.setStreetName(fields.get(Streetname));
//					pa.setStreetNumber(fields.get(StreetNr));
//					pa.setCountry(Country.LUXEMBOURG);
//					phy.setPhysicianAddress(pa);
//					
//					write("creating physician: " + phy);
//					phy = officeManager.savePhysician(phy);
//					
//					// create account if data is available
//					try
//					{
//						Settlement settlement = new Settlement();
//						Account acc = new Account();
//						acc.setBankname(fields.get(Bankname));
//						acc.setBic(fields.get(BICCode));
//						acc.setIban(fields.get(IBANCode));
//						acc.setHolder(phy);
//						settlement.setTransferAccount(acc);
//						
//						write("creating settlement: " + settlement);
//						settlementInterface.saveSettlement(settlement);
//					}
//					catch (Exception e)
//					{
//						write("unable to create bank account for: " + phy);
//					}
//					createdUsers.add(sb.toString());
//					
//				}
//				catch (Exception e)
//				{
//					write(e.getLocalizedMessage());
//					logger.log(Level.ERROR, e.getMessage(), e);
//				}
//				
//				// read next line
//				fields = reader.readFields();
//			}
//			
//			write("-------- ALL USERS CREATED --------");
//			write("-------- PASTE EVERYTHING BELOW THIS INTO Excel --------");
//			write("Name,Login,Password");
//			for (String user : createdUsers)
//			{
//				write(user);
//			}
//			write("-------- DONE --------");
//			
//			cancelButton.setText("Close");
//			okButton.setEnabled(false);
//			
//		}
//		catch (Exception e)
//		{
//			logger.log(Level.ERROR, e.getMessage(), e);
//		}
//	}
//	
//	
//	/**
//	 * Generate a code.
//	 * 
//	 * @param digits
//	 * @return
//	 */
//	private String generateCode(int digits)
//	{
//		StringBuffer buff = new StringBuffer();
//		double r = 31;
//		int count = 0;
//		while (count < digits)
//		{
//			r = Math.random() * 1000;
//			if ((r > 48 && r < 56) || (r > 65 && r < 90) || (r > 97 && r < 122))
//			{
//				buff.append("" + (char) ((int) r));
//				count++;
//			}
//		}
//		
//		return buff.toString();
//	}
//	
//	
//	private void write(String string)
//	{
//		this.textArea.append(string + "\n");
//		this.textArea.setCaretPosition(textArea.getDocument().getLength());
//		// System.out.println(string);
//	}
//	
//	
//	public void actionPerformed(ActionEvent e)
//	{
//		if (e.getSource().equals(this.fileButton))
//		{
//			if (jfileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
//			{
//				
//				this.file = jfileChooser.getSelectedFile();
//				this.fileButton.setText("file: " + this.file.getName());
//			}
//		}
//		else if (e.getSource().equals(this.okButton))
//		{
//			new Thread()
//			{
//				
//				public void run()
//				{
//					textArea.setText("");
//					runImport(file);
//				}
//			}.start();
//		}
//		else if (e.getSource().equals(this.cancelButton))
//		{
//			this.dispose();
//		}
//	}
//	
//	
//	/**
//	 * @param args
//	 */
//	public static void main(String[] args)
//	{
//		try
//		{
//			// login to jboss
//			Properties properties = new Properties();
//			properties.load(new FileInputStream(new File("conf/GECAMed.properties")));
//			// copy properties to the system properties
//			for (Object element : properties.keySet())
//			{
//				System.setProperty((String) element, properties.getProperty((String) element));
//			}
//			JaasJbossConfiguration.activateConfiguration();
//			CallbackHandler ch = new LoginCallbackHandler("admin", "admin");
//			LoginContext lc = new LoginContext("gecam_login", ch);
//			lc.login();
//			new InitialContext();
//			
//			new PhysicianCVSImport();
//			
//		}
//		catch (Exception e)
//		{
//			logger.log(Level.ERROR, e.getMessage(), e);
//		}
//	}
//}
