package ui.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import classes.AbstractCpsObject;
import classes.HolonElement;
import classes.HolonObject;
import ui.controller.Control;

/**
 * Popup for adding a Holon Object to a Category.
 * 
 * @author Gruppe14
 */
public class AddObjectPopUp extends JDialog {

	private static final long serialVersionUID = 1L;
	private final JPanel contentPanel = new JPanel();
	private AddElementPopUp addElement;
	private JTextField objectName;
	private JTextField sourcePath;
	private ArrayList<HolonElement> hElements;
	private DefaultListModel listModel;
	private JList list;
	private String imagePath;
	private HolonObject theObject;
	private Control controller;
	private File selectedFile = null;
	private String filePath = " ";
	private String givenCategory;
	private JLabel lblImagePreview;
	private AbstractCpsObject toEdit;
	private boolean editState;
	private boolean imageChanged = false;

	/**
	 * Launch the application.
	 * 
	 * @param args
	 *            standard
	 */
	public static void main(String[] args) {
		try {
			AddObjectPopUp dialog = new AddObjectPopUp(false, null, null);
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 * 
	 * @param edit
	 *            true if edit
	 * @param obj
	 *            the object
	 * @param cat
	 *            the categorie
	 */
	public AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat) {
		toEdit = obj;
		editState = edit;
		this.setIconImage(new ImageIcon(this.getClass().getResource("/Images/Dummy_House.png")).getImage()
				.getScaledInstance(30, 30, Image.SCALE_SMOOTH));
		setBounds(100, 100, 450, 342);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		hElements = new ArrayList<HolonElement>();
		this.setTitle(Languages.getLanguage()[58]);
		{
			JLabel lblName = new JLabel(Languages.getLanguage()[59]);
			lblName.setHorizontalAlignment(SwingConstants.CENTER);
			lblName.setBounds(28, 21, 76, 14);
			contentPanel.add(lblName);
		}
		{
			objectName = new JTextField();
			objectName.addKeyListener(new KeyListener() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void keyReleased(KeyEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void keyTyped(KeyEvent e) {
					objectName.setBackground(Color.WHITE);
				}
			});
			if (edit) {
				objectName.setText(obj.getName());
			}
			objectName.setBounds(98, 18, 172, 20);
			contentPanel.add(objectName);
			objectName.setColumns(10);
		}
		{
			JButton btnBrowseImage = new JButton(Languages.getLanguage()[60]);
			btnBrowseImage.setBounds(10, 75, 134, 23);
			contentPanel.add(btnBrowseImage);
			btnBrowseImage.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent e) {
					fileChooser();
				}
			});

		}
		{
			lblImagePreview = new JLabel("");
			lblImagePreview.setBounds(295, 3, 50, 50);
			contentPanel.add(lblImagePreview);
		}
		{
			sourcePath = new JTextField();
			sourcePath.addKeyListener(new KeyListener() {
				@Override
				public void keyPressed(KeyEvent arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void keyReleased(KeyEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void keyTyped(KeyEvent e) {
					sourcePath.setBackground(Color.WHITE);
				}
			});
			if (edit) {
				File checkPath = new File(obj.getImage());
				if (checkPath.exists()) {
					selectedFile = new File(obj.getImage());
				} else {
					selectedFile = new File(this.getClass().getResource(obj.getImage()).getFile());
				}
				filePath = selectedFile.getAbsolutePath();
				sourcePath.setText(filePath);
				ImageIcon icon = new ImageIcon(
						new ImageIcon(filePath).getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH));
				if (icon != null)
					lblImagePreview.setIcon(icon);
			}
			sourcePath.setBounds(148, 77, 271, 20);
			contentPanel.add(sourcePath);
			sourcePath.setColumns(10);
		}
		{
			JButton btnAddDefaultElement = new JButton(Languages.getLanguage()[61]);
			btnAddDefaultElement.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					addElement = new AddElementPopUp();
					addElement.setActualCps(toEdit);
					addElement.setVisible(true);
					HolonElement hl = addElement.getElement();
					if (hl != null) {
						hl.setSav(givenCategory);
					}
					hl.setObj(objectName.getText());
					addElement(hl);
				}
			});

			btnAddDefaultElement.setBounds(270, 144, 142, 23);
			contentPanel.add(btnAddDefaultElement);
		}
		{
			JScrollPane scrollPane = new JScrollPane();
			scrollPane.setBounds(10, 114, 236, 150);
			contentPanel.add(scrollPane);
			{

				listModel = new DefaultListModel();

				/*
				 * HolonElement hel = new HolonElement("Test", 100, 5); String
				 * name = hel.getEleName(); for (int i = 0; i < 11; i++) {
				 * hel.setEleName(name + i); addElement(hel); }
				 */
				list = new JList(listModel);
				scrollPane.setViewportView(list);
			}
		}
		if (edit) {
			for (HolonElement e : ((HolonObject) obj).getElements()) {
				addElement(e);
			}
		}
		{
			JButton btnNewButton = new JButton(Languages.getLanguage()[62]);
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					int selectedIndex = list.getSelectedIndex();
					if (selectedIndex != -1) {
						listModel.remove(selectedIndex);
						hElements.remove(selectedIndex);
					}
				}
			});
			btnNewButton.setBounds(270, 182, 142, 27);
			contentPanel.add(btnNewButton);
		}

		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");
				okButton.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent e) {
						Component frame = null;
						if (objectName.getText().length() > 0) {
							if (sourcePath.getText().equals(filePath)) {
								imagePath = filePath;
								if (imageChanged)
									copieFile();
								imageChanged = false;
								// theObject = new
								// HolonObject(objectName.getText());
								// theObject.setElements(hElements);
								// theObject.setImage(imagePath);
								if (editState) {
									controller.delObjectCategory(givenCategory, toEdit.getName());
									controller.addObject(controller.searchCategory(givenCategory), objectName.getText(),
											hElements, imagePath);
								} else {
									controller.addObject(controller.searchCategory(givenCategory), objectName.getText(),
											hElements, imagePath);
								}
								// controller.addObjectCategory(controller.searchCategory(givenCategory),
								// theObject);
								//
								// System.out.println(theObject.getImage());
								System.out.println(givenCategory);
								dispose();
							} else {
								sourcePath.setBackground(new Color(255, 50, 50));
							}
						} else {
							objectName.setBackground(new Color(255, 50, 50));
							if (!sourcePath.getText().equals(filePath))
								sourcePath.setBackground(new Color(255, 50, 50));

						}
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton(Languages.getLanguage()[63]);
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						dispose();
					}
				});
			}
		}
	}

	/**
	 * adds a Holon Element.
	 * 
	 * @param hl
	 *            the HolonElement
	 */
	public void addElement(HolonElement hl) {
		hElements.add(hl);
		listModel.addElement(hl.getAmount() + "x: " + hl.getEleName() + " " + hl.getEnergy() + "U");
	}

	/**
	 * Choose the file.
	 */
	protected void fileChooser() {
		// TODO Auto-generated method stub
		JFileChooser fileChooser = new JFileChooser();
		FileNameExtensionFilter filter = new FileNameExtensionFilter("png, jpg or jpeg", "png", "jpg", "jpeg");
		fileChooser.setFileFilter(filter);
		int returnValue = fileChooser.showOpenDialog(null);
		if (returnValue == JFileChooser.APPROVE_OPTION) {
			selectedFile = fileChooser.getSelectedFile();
			filePath = selectedFile.getAbsolutePath();
			sourcePath.setText(filePath);
			ImageIcon icon = new ImageIcon(
					new ImageIcon(filePath).getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH));
			lblImagePreview.setIcon(icon);
			imageChanged = true;
		} else {
			System.out.println("Failed to Load");
		}

	}

	/**
	 * Copies the File.
	 */
	protected void copieFile() {
		InputStream inStream = null;
		OutputStream outStream = null;
		try {
			File source = new File(filePath);
			File dest = new File(System.getProperty("user.home") + "/HolonGUI/Images/");
			dest.mkdirs();
			dest = new File(dest, selectedFile.getName());
			imagePath = "" + dest;

			inStream = new FileInputStream(source);
			outStream = new FileOutputStream(dest);
			byte[] buffer = new byte[1024];

			int length;
			while ((length = inStream.read(buffer)) > 0) {
				outStream.write(buffer, 0, length);
			}

			if (inStream != null)
				inStream.close();
			if (outStream != null)
				outStream.close();
			System.out.println("File Copied..");
		} catch (IOException eex) {
			eex.printStackTrace();
		}
	}

	/**
	 * Edit the Information.
	 * 
	 * @param obj
	 *            the CpsObject
	 */
	public void editInformation(HolonObject obj) {
		objectName.setText(obj.getName());
	}

	/**
	 * Get Jar Containing Folder.
	 * 
	 * @param aclass
	 *            aClass
	 * @return String
	 * @throws Exception
	 *             Exception
	 */
	public static String getJarContainingFolder(Class aclass) throws Exception {
		CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();

		File jarFile;

		if (codeSource.getLocation() != null) {
			jarFile = new File(codeSource.getLocation().toURI());
		} else {
			String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
			String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
			jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
			jarFile = new File(jarFilePath);
		}
		return jarFile.getParentFile().getAbsolutePath();
	}

	/**
	 * Return the Object.
	 * 
	 * @return the CpsObject
	 */
	public HolonObject getObject() {
		return theObject;
	}

	/**
	 * Sets the Controller.
	 * 
	 * @param controller
	 *            the controller
	 */
	public void setController(Control controller) {
		this.controller = controller;
	}

	/**
	 * Set the Category.
	 * 
	 * @param cat
	 *            the Category
	 */
	public void setCategory(String cat) {
		givenCategory = cat;
	}
}
