package ui.view.additional.popup;

import java.awt.BorderLayout;
import java.awt.Choice;
import java.io.File;
import java.io.IOException;

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

import classes.Category;
import classes.HolonElement;
import classes.HolonObject;
import classes.Pair;
import model.Model;
import ui.controller.Control;
import utility.ImageImport;

/**
 * PopUp for creating Holon Object Template.
 * 
 * @author Gruppe 07 (A.T.M-B)
 */
public class CreateTemplatePopUp extends JDialog {

	private static final long serialVersionUID = 1L;

	/**
	 * Template HolonObject
	 */
	private HolonObject template;

	/**
	 * HolonElementList
	 */
	DefaultListModel<String> listModel;

	/**
	 * HolonElement List
	 */
	JList<String> list;

	/**
	 * Category the Template should be inserted into
	 */
	private String category;

	// Template Attributes

	// PopUp Parts
	private Control controller;

	/**
	 * Category Selection
	 */
	Choice choice;

	/**
	 * name textfield
	 */
	private JTextField textField_name;

	/**
	 * textField for path
	 */
	private JTextField textField_imagePath;

	/**
	 * Image Preview
	 */
	JLabel lblImagePreview;

	/**
	 * parent Frame
	 */
	JFrame parent;
	/**
	 * Create the dialog.
	 * 
	 * @param edit
	 *            true if edit
	 * @param obj
	 *            the object
	 * @param model
	 * @param cat
	 *            the categorie
	 */
	public CreateTemplatePopUp(HolonObject obj, Model model,
			JFrame parentFrame, Control controller) {
		setResizable(false);
		/*
		 * use Category Controller an stuff lul
		 */

		/*
		 * initialize Data
		 */
		template = new HolonObject(obj);
		this.parent = parentFrame;
		this.controller = controller;
		/*
		 * create Frame and GUI
		 */
		setIconImage(ImageImport.loadImage("/Images/Holeg.png", 30, 30));
		setBounds(100, 100, 476, 344);
		setLocationRelativeTo(parentFrame);
		getContentPane().setLayout(new BorderLayout());

		/**
		 * Content Panel
		 */
		JPanel contentPanel = new JPanel();
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);

		/**
		 * Category Label
		 */
		JLabel lblCategory = new JLabel("Category:");
		lblCategory.setBounds(12, 13, 68, 22);
		contentPanel.add(lblCategory);

		/**
		 * Category Choice
		 */
		choice = new Choice();
		choice.setBounds(86, 13, 172, 22);
		contentPanel.add(choice);
		// add categories
		if (model.getCategories().size() == 0)// if no categorie exist: create
												// new Template Category
			try {
				this.controller.addCategory("Template");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		// add Categories to the choice
		for (Category c : model.getCategories())
			choice.add(c.getName());

		/**
		 * Name Label
		 */
		JLabel lblName = new JLabel("Name:");
		lblName.setBounds(12, 48, 56, 16);
		contentPanel.add(lblName);

		/**
		 * Name Textfield
		 */
		textField_name = new JTextField();
		textField_name.setBounds(86, 48, 172, 22);
		contentPanel.add(textField_name);
		textField_name.setColumns(10);
		textField_name.setText(template.getName());

		/**
		 * Image Path Lable
		 */
		JLabel lblImage = new JLabel("Image:");
		lblImage.setBounds(12, 89, 56, 16);
		contentPanel.add(lblImage);

		/**
		 * Image Path Text Field
		 */
		textField_imagePath = new JTextField();
		textField_imagePath.setBounds(86, 86, 172, 22);
		contentPanel.add(textField_imagePath);
		textField_imagePath.setColumns(10);
		textField_imagePath.setText(template.getImage());

		/**
		 * Browse Image Button
		 */
		JButton btnBrowseImage = new JButton("BrowseImage");
		btnBrowseImage.setBounds(268, 85, 117, 25);
		contentPanel.add(btnBrowseImage);
		btnBrowseImage.addActionListener(actionevent -> {
			fileChooser();
		});

		/**
		 * Image Preview
		 */
		lblImagePreview = new JLabel("Image Preview");
		lblImagePreview.setIcon(new ImageIcon(ImageImport.loadImage(
				template.getImage(), 62, 62)));
		lblImagePreview.setBounds(298, 13, 62, 62);
		contentPanel.add(lblImagePreview);

		/**
		 * Holon Element List
		 */
		listModel = new DefaultListModel<String>();

		/**
		 * Add Elements to List
		 */
		for (HolonElement he : template.getElements())
			listModel.addElement(he.getAmount() + " * " + he.getEleName()
					+ ": " + he.getMaximumEnergy() + "U");

		/**
		 * Add ScrollPane to List
		 */
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(22, 118, 236, 150);
		contentPanel.add(scrollPane);
		list = new JList<String>(listModel);
		scrollPane.setViewportView(list);

		/**
		 * Delete Element Button
		 */
		JButton btnDeleteElement = new JButton("Delete Element");
		btnDeleteElement.setBounds(268, 228, 140, 25);
		contentPanel.add(btnDeleteElement);
		btnDeleteElement.addActionListener(e -> removeElement());

		/**
		 * Edit Element Button
		 */
		JButton btnEditElement = new JButton("Edit Element");
		btnEditElement.setBounds(268, 190, 140, 25);
		contentPanel.add(btnEditElement);
		btnEditElement.addActionListener(e -> editElement());

		/**
		 * Add Element Button
		 */
		JButton btnAddElement = new JButton("Add Element");
		btnAddElement.setBounds(268, 152, 140, 25);
		contentPanel.add(btnAddElement);
		btnAddElement.addActionListener(e -> addElement());

		/**
		 * Cancel Button
		 */
		JButton btnCancel = new JButton("Cancel");
		btnCancel.setBounds(384, 277, 74, 25);
		contentPanel.add(btnCancel);
		btnCancel.addActionListener(e -> dispose());

		/**
		 * Add Template Button
		 */
		JButton btnAddTemplate = new JButton("Add Template");
		btnAddTemplate.setBounds(75, 271, 113, 25);
		contentPanel.add(btnAddTemplate);
		btnAddTemplate.addActionListener(e -> createTemplate());

		/**
		 * Title
		 */
		setTitle("Create Template Menu");

	}

	/**
	 * Choose the file.
	 */
	private void fileChooser() {
		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) {
			File selectedFile = fileChooser.getSelectedFile();
			String filePath = selectedFile.getAbsolutePath();
			textField_imagePath.setText(filePath);
			ImageIcon icon = new ImageIcon(ImageImport.loadImage(filePath, 62,
					62));
			lblImagePreview.setIcon(icon);
		} else {
			System.out.println("Failed to Load");
		}

	}

	/**
	 * create the template and add it to the category
	 */
	private void createTemplate() {
		try {
			template.setName(textField_name.getText());
			template.setImage(textField_imagePath.getText());
			template.getElements().forEach(
					ele -> ele.setSaving(new Pair<String, String>(choice
							.getSelectedItem(), template.getName())));
			controller.addObject(controller.searchCategory(choice
					.getItem(choice.getSelectedIndex())), template.getName(),
					template.getElements(), template.getImage());
			this.dispose();
		} catch (IOException e) {
			System.out
					.println("Could not create Template: Category not found!");
			e.printStackTrace();
		}
	}

	/**
	 * Add an Holon Element to the template
	 */
	private void addElement() {
		AddElementPopUp popUp = new AddElementPopUp(parent);
		popUp.setActualCps(template);
		popUp.setVisible(true);
		HolonElement he = popUp.getElement();
		if (he != null) {
			listModel.addElement(he.getAmount() + " * " + he.getEleName()
					+ ": " + he.getMaximumEnergy() + "U");
			template.addElement(he);
			he.setSaving(new Pair<>(category, textField_name.getText()));
		}
	}

	/**
	 * Removes the Selected Element from the template
	 */
	private void removeElement() {
		int index = list.getSelectedIndex();
		if (index == -1)
			return;
		template.deleteElement(index);
		listModel.remove(index);
	}

	/**
	 * Edits the selected HolonElement
	 */
	private void editElement() {
		int index = list.getSelectedIndex();
		if (index == -1)
			return;
		
		AddElementPopUp popUp = new AddElementPopUp(parent);
		popUp.setActualCps(template);
		popUp.setElement(template.getElements().get(index));
		popUp.setVisible(true);
		HolonElement he = popUp.getElement();
		if (he != null) {
			listModel.remove(index);
			listModel.addElement(he.getAmount() + " * " + he.getEleName()
					+ ": " + he.getMaximumEnergy() + "U");
			template.deleteElement(index);
			template.addElement(he);
			he.setSaving(new Pair<>(category, textField_name.getText()));
		}
	}

}
