package ui.view;

import classes.CpsUpperNode;
import ui.controller.Control;
import ui.model.Model;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.*;

/**
 * Popup for setting the Background Image for the current View.
 **/
public class BackgroundPopUp extends JDialog {

    // Modes
    public static final int IMAGE_PIXELS = 0, STRETCHED = 1, CUSTOM = 2;
    /**
     *
     */
	private static final long serialVersionUID = 1L;
	private final JTextField textPath = new JTextField("");
	private final JButton btnBrowse = new JButton("Browse");
	private final JPanel panelBrowse = new JPanel();
	private final JPanel panelOK = new JPanel();
	private final JButton btnOK = new JButton("OK");
	private final JLabel lblImage = new JLabel();
	private final JButton btnCancel = new JButton("Cancel");
	private final JPanel panelRadio = new JPanel();
	private final JRadioButton rdbtnImagePixel = new JRadioButton("Use Image Size");
	private final JRadioButton rdbtnStretched = new JRadioButton("Strech Image");
	private final JRadioButton rdbtnCustom = new JRadioButton("Custom Size");
	private final JButton removeImageBtn = new JButton("Remove Background Image");
	private final JPanel panel = new JPanel();
	private final JTextField imageWidth = new JTextField();
	private final JTextField imageHeight = new JTextField();
	JFileChooser fileChooser;
    private JPanel panelImageRadio = new JPanel();
    private String path = "";
    private boolean imageChanged = false;
    private ImageIcon icon = null;
    private double imgScale = 1;
    private boolean imageBtnClearedPressed = false;
    private int mode = 0;

    public BackgroundPopUp(Model model, Control controller, MyCanvas canvas, CpsUpperNode uNode, JFrame parentFrame) {
        super((java.awt.Frame) null, true);
		getContentPane().setBackground(Color.WHITE);
		this.setTitle("Set View Background");
		// Show background Image
		if (canvas != null) {
			path = model.getCanvasImagePath();
		} else if (uNode != null) {
			path = uNode.getImagePath();
		}
		if (!path.isEmpty()) {
			textPath.setText(path);
			icon = new ImageIcon(path);
			imageWidth.setText("" + icon.getIconWidth());
			imageHeight.setText("" + icon.getIconHeight());
		}
		this.setIconImage(Util.loadImage(this,"/Images/Dummy_House.png",30,30));
		setBounds(100, 100, 600, 340);
        setLocationRelativeTo(parentFrame);

		panelBrowse.setBorder(null);
		panelImageRadio.setBorder(null);
		panelOK.setBorder(null);
		panelRadio.setBorder(null);

		getContentPane().add(panelImageRadio, BorderLayout.CENTER);
		panelImageRadio.setLayout(new BorderLayout(0, 0));
		lblImage.setBackground(Color.WHITE);
		lblImage.setHorizontalAlignment(SwingConstants.LEFT);

		panelImageRadio.add(lblImage, BorderLayout.CENTER);

		panelImageRadio.add(panelRadio, BorderLayout.EAST);

		// Radio Buttons
		panelRadio.setLayout(new GridLayout(0, 1, 0, 0));

		rdbtnImagePixel.setBackground(Color.WHITE);
		rdbtnImagePixel.setSelected(true);

		panelRadio.add(rdbtnImagePixel);
		rdbtnStretched.setBackground(Color.WHITE);

		panelRadio.add(rdbtnStretched);
		panelBrowse.setBackground(Color.WHITE);

		ButtonGroup bgroup = new ButtonGroup();
		bgroup.add(rdbtnImagePixel);
		bgroup.add(rdbtnStretched);
		panelRadio.add(rdbtnCustom);
		rdbtnCustom.setBackground(new Color(255, 255, 255));
		bgroup.add(rdbtnCustom);
		panel.setBackground(Color.WHITE);

		panelRadio.add(panel);
		panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		panel.add(imageWidth);
		imageWidth.setColumns(10);
		panel.add(imageHeight);
		imageHeight.setColumns(10);

		// remove BackgroundImage Button
		removeImageBtn.setBackground(Color.WHITE);
		removeImageBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				path = "";
				textPath.setText("");
				imageBtnClearedPressed = true;
				lblImage.setIcon(null);
			}
		});
		JPanel removePanel = new JPanel();
		removePanel.add(removeImageBtn);
		removePanel.setBackground(Color.WHITE);
		panelRadio.add(removePanel);

		// Browse Panel
		getContentPane().add(panelBrowse, BorderLayout.NORTH);
		panelBrowse.setLayout(new BorderLayout(0, 0));
		panelBrowse.add(btnBrowse, BorderLayout.WEST);

		// Browse Row Functions
		btnBrowse.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				fileChooser = new JFileChooser();
				FileNameExtensionFilter filter = new FileNameExtensionFilter("png, jpg or jpeg", "png", "jpg", "jpeg");
				fileChooser.setFileFilter(filter);
				if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
					path = fileChooser.getSelectedFile().getPath();
					textPath.setText(path);
					icon = new ImageIcon(textPath.getText());
					imageWidth.setText("" + icon.getIconWidth());
					imageHeight.setText("" + icon.getIconHeight());

					imageChanged = true;

					// Calculate the Image scale to fit the Panel
					if (Math.min(panelImageRadio.getWidth() - panelRadio.getWidth(),
							panelImageRadio.getHeight()) == (panelImageRadio.getWidth() - panelRadio.getWidth())) {
						imgScale = (double) Math.min(icon.getIconWidth(), icon.getIconHeight())
								/ panelImageRadio.getWidth();
					} else {
						imgScale = (double) Math.min(icon.getIconWidth(), icon.getIconHeight())
								/ panelImageRadio.getHeight();
					}

					lblImage.setIcon(new ImageIcon(
							new ImageIcon(path).getImage().getScaledInstance((int) (icon.getIconWidth() / imgScale),
									(int) (icon.getIconHeight() / imgScale), java.awt.Image.SCALE_FAST)));
				}
			}
		});
		textPath.setEditable(false);

		panelBrowse.add(textPath, BorderLayout.CENTER);
		textPath.setColumns(20);
		panelOK.setBackground(Color.WHITE);

		getContentPane().add(panelOK, BorderLayout.SOUTH);
		panelOK.add(btnOK);
		btnOK.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// picture selected?
				if (!path.isEmpty()) {
					if (rdbtnImagePixel.isSelected()) {
						mode = 0;
					} else if (rdbtnStretched.isSelected()) {
						mode = 1;
					} else if (rdbtnCustom.isSelected()) {
						mode = 2;
					}

					if (canvas != null) {
						if (imageChanged) {
							copieImage();
						}
						controller.setBackgroundImage(path, mode, Integer.parseInt(imageWidth.getText()),
								Integer.parseInt(imageHeight.getText()));
						canvas.repaint();
					} else if (uNode != null) {
						if (imageChanged) {
							copieImage();
						}
						uNode.setBackgroundImage(path, mode, Integer.parseInt(imageWidth.getText()),
								Integer.parseInt(imageHeight.getText()));
					}
					dispose();
				} else if (imageBtnClearedPressed) {
					if (canvas != null) {
						controller.setBackgroundImage(path, mode, Integer.parseInt(imageWidth.getText()),
								Integer.parseInt(imageHeight.getText()));
						canvas.repaint();
					} else if (uNode != null) {
						uNode.setBackgroundImage(path, mode, Integer.parseInt(imageWidth.getText()),
								Integer.parseInt(imageHeight.getText()));
					}
					dispose();
				} else {
					JOptionPane.showMessageDialog(null, "No image selected!", "Warning!", JOptionPane.WARNING_MESSAGE);
				}
			}
		});

		panelOK.add(btnCancel);
		btnCancel.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		this.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				if (icon != null) {
					// Calculate the Image scale to fit the Panel
					if (Math.min(panelImageRadio.getWidth() - panelRadio.getWidth(),
							panelImageRadio.getHeight()) == (panelImageRadio.getWidth() - panelRadio.getWidth())) {
						imgScale = (double) Math.min(icon.getIconWidth(), icon.getIconHeight())
								/ panelImageRadio.getWidth();
					} else {
						imgScale = (double) Math.min(icon.getIconWidth(), icon.getIconHeight())
								/ panelImageRadio.getHeight();
					}

					lblImage.setIcon(new ImageIcon(
							new ImageIcon(path).getImage().getScaledInstance((int) (icon.getIconWidth() / imgScale),
									(int) (icon.getIconHeight() / imgScale), java.awt.Image.SCALE_SMOOTH)));
				}
			}
		});
	}

	protected void copieImage() {
		InputStream inStream = null;
		OutputStream outStream = null;
		try {
			File source = new File(path);
			File dest = new File(System.getProperty("user.home") + "/HolonGUI/BackgroundImages/");
			dest.mkdirs();
			dest = new File(dest, source.getName());
			path = "" + 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();

		} catch (IOException eex) {
			eex.printStackTrace();
		}
	}
}
