package net.sf.anpr.rcp.widget;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.anpr.rcp.Platform;
import net.sf.anpr.rcp.model.PerspectiveBean;
import net.sf.anpr.rcp.service.Services;
import net.sf.anpr.rcp.util.SwingResourceManager;
import net.sf.anpr.rcp.util.SwingUtil;

public class OpenPerspectiveDialog extends JDialog{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final static Logger LOGGER=LoggerFactory.getLogger(OpenPerspectiveDialog.class);
	private DefaultListModel model;
	private JButton okButton;
	private JButton cancelButton;
	private JList perspectiveJList;
	private JTextArea descLabel;
	private JButton deleteButton;
	private JImagePanel imagePanel;

	public OpenPerspectiveDialog() {
		super(Platform.current().getApplicationWindow());
		this.setTitle("Open perspective");
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		this.setIconImage(SwingResourceManager.getImage(OpenPerspectiveDialog.class, "perspective.png"));
		this.setResizable(true);
		setSize(800, 600);
		
		setModal(true);
		getContentPane().setLayout(new BorderLayout(0, 0));
		
		JSplitPane splitPane = new JSplitPane();
		getContentPane().add(splitPane, BorderLayout.CENTER);
		splitPane.setDividerLocation(0.3);
		
		JScrollPane scrollPane = new JScrollPane();
		splitPane.setLeftComponent(scrollPane);
		
		model=new DefaultListModel();
		perspectiveJList = new JList(model);
		perspectiveJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION);
		scrollPane.setViewportView(perspectiveJList);
		
		JPanel panel = new JPanel();
		splitPane.setRightComponent(panel);
		panel.setLayout(new BorderLayout(0, 0));
		
		imagePanel = new JImagePanel();
		panel.add(imagePanel, BorderLayout.CENTER);
		
		descLabel = new JTextArea();
		descLabel.setRows(8);
		descLabel.setEditable(false);
		panel.add(SwingUtil.scrollView(descLabel), BorderLayout.SOUTH);
		
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				deleteButton = new JButton("Delete Selected");
				buttonPane.add(deleteButton);
			}
			{
				okButton = new JButton("OK");
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				cancelButton = new JButton("Cancel");
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
		
		
		addListeners();
		initData();
	}

	private void initData() {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				model.clear();
				
				List<PerspectiveBean> beanList=Services.perspectiveService.listAll();
				for(PerspectiveBean b:beanList){
					model.addElement(b);
				}
			}
		});
	}

	private void addListeners() {
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						PerspectiveBean bean=(PerspectiveBean)perspectiveJList.getSelectedValue();
						if(bean==null){
							JOptionPane.showMessageDialog(null, "Please select one saved prespective", "Error", JOptionPane.WARNING_MESSAGE);
							return ;
						}
						dispose();
						
						try {
							String xml=bean.getXml();
							ByteArrayInputStream in=new ByteArrayInputStream(xml.getBytes());
							Platform.current().getApplicationWindow().getDockingDesktop().readXML(in);
							in.close();
							
							//set selected perspective to alive, it will open as default next time
							bean.setFlag("current,");
							Services.perspectiveService.setAsDefault(bean);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		});
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		deleteButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				PerspectiveBean bean=(PerspectiveBean)perspectiveJList.getSelectedValue();
				if(bean==null){
					return ;
				}
				model.removeElementAt(perspectiveJList.getSelectedIndex());
				Services.perspectiveService.delete(bean);
				descLabel.setText("");
				imagePanel.setImage(null);
			}
		});
		perspectiveJList.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				if(e.getValueIsAdjusting()){
					return ;
				}
				final PerspectiveBean bean=(PerspectiveBean)perspectiveJList.getSelectedValue();
				if(bean==null){
					return ;
				}
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						try {
							LOGGER.debug("{}", bean);
							descLabel.setText(bean.getDescription());
							if(bean.getSnapshot()!=null&&bean.getSnapshot().length()>0){
								byte[] bytes=Base64.decodeBase64(bean.getSnapshot());
								ByteArrayInputStream in=new ByteArrayInputStream(bytes);
								BufferedImage image = ImageIO.read(in);
								imagePanel.setImage(image);
							}
							else {
								imagePanel.setImage(null);
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				});
			}
		});
	}
	
}
