package com.baselet.standalone.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JComboBox;

import com.baselet.diagram.CurrentDiagram;
import com.baselet.diagram.DiagramHandler;
import com.baselet.gui.BaseGUI;
import com.baselet.gui.CurrentGui;

public class DiagramTypeListener implements ActionListener, MouseWheelListener {

	@SuppressWarnings("unchecked")
	@Override
	public void actionPerformed(ActionEvent e) {

		if (e.getSource() instanceof JComboBox) {
			handle((JComboBox<String>) e.getSource());
		}
	}

	@Override
	public void mouseWheelMoved(MouseWheelEvent e) {
		if (e.getSource() instanceof JComboBox) {
			JComboBox<String> comboBox = (JComboBox<String>) e.getSource();
			int newIndex = comboBox.getSelectedIndex() + e.getWheelRotation(); // wheelrotation is -1 (up) or +1 (down)
			if (comboBox.getItemAt(newIndex) != null) {
				comboBox.setSelectedIndex(newIndex);
			}
		}
	}

	private void handle(JComboBox<String> comboBox) {
		BaseGUI gui = CurrentGui.getInstance().getGui();
		DiagramHandler diagramHandler = CurrentDiagram.getInstance().getDiagramHandler();

		if (diagramHandler != null) {
			String lastDiagType = diagramHandler.getCurrentDiagType();
			String diagramType = comboBox.getSelectedItem().toString().trim();
			if (diagramHandler.isLegalToChangeDiagType(diagramType, lastDiagType)) {
				gui.initZoom();
				diagramHandler.updateDiagram(diagramType);
			}
			else {
				comboBox.setSelectedItem(lastDiagType);
			}
		}
	}
}
