/*
 * 
 *               Panbox - encryption for cloud storage 
 *      Copyright (C) 2014-2015 by Fraunhofer SIT and Sirrix AG 
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Additonally, third party code may be provided with notices and open source
 * licenses from communities and third parties that govern the use of those
 * portions, and any licenses granted hereunder do not alter any rights and
 * obligations you may have under such open source licenses, however, the
 * disclaimer of warranty and limitation of liability provisions of the GPLv3 
 * will apply to all the product.
 * 
 */
package org.panbox.desktop.common.gui;

import ezvcard.VCard;
import ezvcard.property.StructuredName;

import org.panbox.Settings;
import org.panbox.core.identitymgmt.AbstractAddressbookManager;
import org.panbox.desktop.common.PanboxClient;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author palige
 * 
 *         Dialog for importing contacts from a VCard
 */
public class ImportIdentitiesWoPINDialog extends javax.swing.JDialog {

	private static final long serialVersionUID = 7665762037632230830L;
	private PanboxClient client;

	private static final ResourceBundle bundle = ResourceBundle.getBundle(
			"org/panbox/desktop/common/gui/Messages", Settings.getInstance()
					.getLocale()); // NOI18N

	private ListSelectionListener contactSelectionListener = new ListSelectionListener() {

		@Override
		public void valueChanged(ListSelectionEvent e) {
			checkImportability();
		}
	};

	private class VCardNameTableCellRenderer extends DefaultTableCellRenderer {

		/**
		 * 
		 */
		private static final long serialVersionUID = 6913177900407781180L;

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {

			if (value instanceof VCard) {
				VCard vc = (VCard) value;
				StructuredName sn = vc.getStructuredName();
				String name = sn.getGiven() + " " + sn.getFamily() + " ("
						+ vc.getEmails().get(0).getValue() + ")";
				return super.getTableCellRendererComponent(table, name,
						isSelected, hasFocus, row, column);
			} else {
				return super.getTableCellRendererComponent(table, value,
						isSelected, hasFocus, row, column);
			}
		}
	}

	/**
	 * Creates new form ImportIdentitiesDialog
	 */
	public ImportIdentitiesWoPINDialog(PanboxClient client) {
		super(client.getMainWindow());
		this.client = client;
		initComponents();
		
		trustExporterVerifications.setVisible(false);

		importContactsTable.getSelectionModel().addListSelectionListener(
				contactSelectionListener);
	}

	public ImportIdentitiesWoPINDialog(PanboxClient client, File identityFile) {
		this(client);
		fileLocTextField.setText(identityFile.getAbsolutePath());
		loadVCardFile(identityFile);
	}

	private void checkImportability() {
		ListSelectionModel model = (ListSelectionModel) importContactsTable
				.getSelectionModel();

		if ((importContactsTable.getRowCount() > 0)
				&& (!model.isSelectionEmpty())) {
			importButton.setEnabled(true);
			return;
		}
		importButton.setEnabled(false);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		fileLocLabel = new javax.swing.JLabel();
		fileLocTextField = new javax.swing.JTextField();
		fileLocButton = new javax.swing.JButton();
		verificationStateLabel = new javax.swing.JLabel();
		trustExporterVerifications = new javax.swing.JCheckBox();
		contactsPanel = new javax.swing.JPanel();
		jScrollPane2 = new javax.swing.JScrollPane();
		importContactsTable = new javax.swing.JTable();
		importButton = new javax.swing.JButton();
		cancelButton = new javax.swing.JButton();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		java.util.ResourceBundle bundle = java.util.ResourceBundle
				.getBundle("org/panbox/desktop/common/gui/Messages"); // NOI18N
		setTitle(bundle.getString("ImportIdentitiesDialog.title")); // NOI18N
		setModal(true);
		setResizable(false);

		fileLocLabel.setText(bundle
				.getString("ImportIdentitiesDialog.fileLocLabel")); // NOI18N

		fileLocTextField.setEditable(false);
		fileLocTextField.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				fileLocTextFieldActionPerformed(evt);
			}
		});

		fileLocButton.setText(bundle
				.getString("ImportIdentitiesDialog.fileLocButton")); // NOI18N
		fileLocButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				fileLocButtonActionPerformed(evt);
			}
		});

		trustExporterVerifications.setText(bundle
				.getString("ImportIdentitiesDialog.importPINCheckbox")); // NOI18N

		contactsPanel
				.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle
						.getString("ImportIdentitiesDialog.contactsPanel.title"))); // NOI18N

		importContactsTable.setModel(new javax.swing.table.DefaultTableModel(
				new Object[][] {

				}, new String[] { "Contact name" }) {
			Class[] types = new Class[] { java.lang.String.class };
			boolean[] canEdit = new boolean[] { false };

			public Class getColumnClass(int columnIndex) {
				return types[columnIndex];
			}

			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});
		importContactsTable.getTableHeader().setReorderingAllowed(false);
		jScrollPane2.setViewportView(importContactsTable);
		importContactsTable
				.getColumnModel()
				.getSelectionModel()
				.setSelectionMode(
						javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		if (importContactsTable.getColumnModel().getColumnCount() > 0) {
			importContactsTable.getColumnModel().getColumn(0)
					.setResizable(false);
			importContactsTable.getColumnModel().getColumn(0)
					.setPreferredWidth(140);
			importContactsTable
					.getColumnModel()
					.getColumn(0)
					.setHeaderValue(
							bundle.getString("ImportIdentitiesDialog.importContactsTable.columnname")); // NOI18N
			importContactsTable.getColumnModel().getColumn(0)
					.setCellRenderer(new VCardNameTableCellRenderer());
		}

		javax.swing.GroupLayout contactsPanelLayout = new javax.swing.GroupLayout(
				contactsPanel);
		contactsPanel.setLayout(contactsPanelLayout);
		contactsPanelLayout.setHorizontalGroup(contactsPanelLayout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						contactsPanelLayout
								.createSequentialGroup()
								.addContainerGap()
								.addComponent(jScrollPane2,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										0, Short.MAX_VALUE).addContainerGap()));
		contactsPanelLayout
				.setVerticalGroup(contactsPanelLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								contactsPanelLayout
										.createSequentialGroup()
										.addComponent(
												jScrollPane2,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												311, Short.MAX_VALUE)
										.addContainerGap()));

		importButton.setText(bundle
				.getString("ImportIdentitiesDialog.importButton")); // NOI18N
		importButton.setEnabled(false);
		importButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				importButtonActionPerformed(evt);
			}
		});

		cancelButton.setText(bundle
				.getString("ImportIdentitiesDialog.cancelButton")); // NOI18N
		cancelButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				cancelButtonActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						javax.swing.GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.TRAILING)
												.addComponent(
														trustExporterVerifications,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE)
												.addGroup(
														javax.swing.GroupLayout.Alignment.LEADING,
														layout.createSequentialGroup()
																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.TRAILING)
																				.addGroup(
																						javax.swing.GroupLayout.Alignment.LEADING,
																						layout.createSequentialGroup()
																								.addGap(387,
																										387,
																										387)
																								.addComponent(
																										verificationStateLabel,
																										javax.swing.GroupLayout.DEFAULT_SIZE,
																										javax.swing.GroupLayout.DEFAULT_SIZE,
																										Short.MAX_VALUE))
																				.addGroup(
																						javax.swing.GroupLayout.Alignment.LEADING,
																						layout.createSequentialGroup()
																								.addComponent(
																										fileLocLabel)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										fileLocTextField)
																								.addGap(6,
																										6,
																										6)))
																.addGap(14, 14,
																		14)
																.addComponent(
																		fileLocButton))
												.addComponent(
														contactsPanel,
														javax.swing.GroupLayout.Alignment.LEADING,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE)
												.addGroup(
														layout.createSequentialGroup()
																.addComponent(
																		importButton)
																.addPreferredGap(
																		javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																.addComponent(
																		cancelButton)))
								.addContainerGap()));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						javax.swing.GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(fileLocLabel)
												.addComponent(
														fileLocTextField,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(fileLocButton))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addComponent(trustExporterVerifications)
								.addGap(12, 12, 12)
								.addComponent(contactsPanel,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(verificationStateLabel,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(cancelButton)
												.addComponent(importButton))
								.addContainerGap()));

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private boolean isVCFVerified;

	private void loadVCardFile(File vcardFile) {
		if (!vcardFile.exists() || !vcardFile.canRead()) {
			JOptionPane.showMessageDialog(this,
					bundle.getString("cannot.read.vcard.file"),
					bundle.getString("error"), JOptionPane.ERROR_MESSAGE);
		} else {
			// load table values
			VCard[] vclist = null;
			// only continue if there are any VCards ..
			if (((vclist = AbstractAddressbookManager
					.readVCardFile(vcardFile)) != null)
					&& (vclist.length > 0)) {
				// remove all existing entries before loading any
				// new ones
				DefaultTableModel tableModel = (DefaultTableModel) importContactsTable
						.getModel();

				tableModel.setRowCount(0);

				for (VCard vc : vclist) {
					tableModel.addRow(new Object[] { vc });
				}
			} else {
				JOptionPane.showMessageDialog(this,
						bundle.getString("error.reading.contacts.file"),
						bundle.getString("error"),
						JOptionPane.ERROR_MESSAGE);
			}

			this.fileLocTextField.setText(vcardFile.getAbsolutePath());
		}
	}

	private void fileLocTextFieldActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_fileLocButtonActionPerformed
	// File file = new File(fileLocTextField.getText());
	// if(!file.exists()) {
	//
	// }
	// loadVCardFile(file);
	}// GEN-LAST:event_fileLocButtonActionPerformed

	private void fileLocButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_fileLocButtonActionPerformed
		JFileChooser fileChooser = new JFileChooser();
		FileNameExtensionFilter filter = new FileNameExtensionFilter(
				"Vcard file (.vcf)", "vcf");
		fileChooser.setFileFilter(filter);
		fileChooser.setMultiSelectionEnabled(false);

		if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
			loadVCardFile(fileChooser.getSelectedFile());

		}
	}// GEN-LAST:event_fileLocButtonActionPerformed

	private void importButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_importButtonActionPerformed
		// get selected items from list and try to start import ..
		List<VCard> selectedContacts = new ArrayList<VCard>();
		DefaultTableModel tableModel = (DefaultTableModel) importContactsTable
				.getModel();
		if (tableModel.getRowCount() == 0) {
			JOptionPane.showMessageDialog(this,
					bundle.getString("list.of.contacts.is.empty"),
					bundle.getString("error"), JOptionPane.ERROR_MESSAGE);
		} else {
			int[] sel = importContactsTable.getSelectedRows();
			for (int i = 0; i < sel.length; i++) {
				VCard v = (VCard) tableModel.getValueAt(sel[i], 0);
				selectedContacts.add(v);
			}

			if (selectedContacts.size() == 0) {
				JOptionPane.showMessageDialog(this,
						bundle.getString("no.contacts.selected"),
						bundle.getString("error"), JOptionPane.ERROR_MESSAGE);
			} else {
				// start import of selected contacts
				client.importContacts(selectedContacts
						.toArray(new VCard[selectedContacts.size()]),
						isVCFVerified);
				this.dispose();
			}
			for (VCard vc : selectedContacts) {
				System.out.println(vc.getStructuredName().getFamily());
			}
		}

	}// GEN-LAST:event_importButtonActionPerformed

	private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cancelButtonActionPerformed
		this.dispose();
	}// GEN-LAST:event_cancelButtonActionPerformed

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton cancelButton;
	private javax.swing.JPanel contactsPanel;
	private javax.swing.JButton fileLocButton;
	private javax.swing.JLabel fileLocLabel;
	private javax.swing.JTextField fileLocTextField;
	private javax.swing.JButton importButton;
	private javax.swing.JTable importContactsTable;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JCheckBox trustExporterVerifications;
	private javax.swing.JLabel verificationStateLabel;
	// End of variables declaration//GEN-END:variables
}
