package vismon.gui;


import info.clearthought.layout.TableLayout;
import org.noos.xing.mydoggy.*;
import org.noos.xing.mydoggy.event.ContentManagerUIEvent;
import org.noos.xing.mydoggy.plaf.MyDoggyToolWindowManager;
import org.noos.xing.mydoggy.plaf.ui.cmp.ContentDialog;
import vismon.data.Session;
import vismon.io.FileHandler;
import vismon.plot.ScatterPlot;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Vismon {

    private JFrame frame;

    private ToolWindowManager eastToolWindowManager;
    private ToolWindowManager westToolWindowManager;
    private ToolWindowManager southToolWindowManager;

    private JPanel northPanel;
    private JPanel eastPanel;
    private JPanel westPanel;
    private JPanel southPanel;

    private JSplitPane splitHorizontal;
    private JSplitPane splitVertical;

    private JMenu fileMenu;
    private JMenu editMenu;
    private JMenu windowMenu;
    private JMenu helpMenu;

    private JMenuItem openMenuItem;
    private JMenuItem openRecentDataMenuItem;
    private JMenuItem openProjectMenuItem;
    private JMenuItem saveProjectMenuItem;
    private JMenuItem saveProjectAsMenuItem;
    private JMenuItem exportWinMenuItem;
    private JMenuItem exportSceMenuItem;

    private JCheckBoxMenuItem overviewWinMenuItem;
    private JCheckBoxMenuItem cplomWinMenuItem;
    private JCheckBoxMenuItem tradeoffsWinMenuItem;
    private JCheckBoxMenuItem visualRefLineWinMenuItem;

    private VisualRefLineDialog visualRefLineDialog;

    private OverviewPanel overviewPanel;
    private CplomPanel cplomPanel;
    private OptionsPanel optionsPanel;
    private TradeoffsPanel tradeoffsPanel;
    private ScenariosPanel scenariosPanel;
    private IndicatorsPanel optionsIndicatorsPanel;
    private IndicatorsPanel tradeoffsIndicatorsPanel;

    private List<ScatterPlot> scatterPlotList;

    private ContentDialog tradeoffsContentDialog;

    protected void run() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                setUp();
                start();
            }
        });
    }

    protected void setUp() {
        overviewPanel = new OverviewPanel();
        cplomPanel = new CplomPanel();
        optionsPanel = new OptionsPanel();
        tradeoffsPanel = new TradeoffsPanel();
        scenariosPanel = new ScenariosPanel();
        optionsIndicatorsPanel = new IndicatorsPanel();
        tradeoffsIndicatorsPanel = new IndicatorsPanel();

        scatterPlotList = new ArrayList<ScatterPlot>();

        ToolTipManager.sharedInstance().setInitialDelay(10);

        initComponents();
        initSplitPane();
        initWestToolWindowManager();
        initEastToolWindowManager();
        initSouthToolWindowManager();
    }

    protected void start() {
        ToolWindow optionsTool = eastToolWindowManager.getToolWindow("Options");
        optionsTool.setVisible(false);
        optionsTool.setIndex(0);

        ToolWindow optionsindicatorTool = eastToolWindowManager.getToolWindow("Indicators");
        optionsindicatorTool.setVisible(false);
        optionsindicatorTool.setIndex(0);

        ToolWindow scenariosTool = southToolWindowManager.getToolWindow("Scenarios");
        scenariosTool.setVisible(false);
        scenariosTool.setIndex(0);

        ToolWindow tradeoffsindicatorTool = southToolWindowManager.getToolWindow("Indicators");
        tradeoffsindicatorTool.setVisible(false);
        tradeoffsindicatorTool.setIndex(0);

        setSubPanelVisibility();
        frame.setVisible(true);
    }

    protected void initComponents() {
        this.frame = new JFrame("Vismon");
        //this.frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
        this.frame.setSize(new Dimension(1280, 720));
        this.frame.setLocation(0, 0);
        this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent windowEvent) {
                Vismon.getVismonInstance().close();
            }
        });

        addMenus();
        setEnabledMenus(false);

        this.frame.getContentPane().setLayout(new TableLayout(new double[][]{{0, -1, 0}, {0, -1, 0}}));
    }

    private void close() {
        frame.setVisible(false);
        frame.dispose();
        System.exit(0);
    }

    private void addMenus() {
        JMenuBar menuBar = new JMenuBar();

        addFileMenu(menuBar);
        addEditMenu(menuBar);
        addWindowMenu(menuBar);
        addHelpMenu(menuBar);

        this.frame.setJMenuBar(menuBar);
    }

    private void setEnabledMenus(boolean enabled) {
        editMenu.setEnabled(enabled);
        windowMenu.setEnabled(enabled);
        helpMenu.setEnabled(enabled);

        openMenuItem.setEnabled(!enabled);
        openRecentDataMenuItem.setEnabled(!enabled);
        openProjectMenuItem.setEnabled(!enabled);

        saveProjectMenuItem.setEnabled(enabled);
        saveProjectAsMenuItem.setEnabled(enabled);
        exportWinMenuItem.setEnabled(enabled);
        exportSceMenuItem.setEnabled(enabled);
    }

    private void addFileMenu(JMenuBar menuBar) {
        final ProgressBar progressBar = new ProgressBar();
        fileMenu = new JMenu("File");

        openMenuItem = new JMenuItem("Open Data");
        openMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                final JFileChooser chooser = new JFileChooser(new File("."));
                final int response = chooser.showOpenDialog(null);
                Thread thread = new Thread() {
                    public void run() {
                        if (response == JFileChooser.APPROVE_OPTION) {
                            progressBar.run();
                            //progressBar.setStatusLabelText("Reading the input file");
                            File f = chooser.getSelectedFile();
                            FileHandler.readDataFile(f);
                        }
                        setEnabledMenus(true);
                        setSubPanelVisibility();

                        //progressBar.setStatusLabelText("Creating the Overview Panel");
                        overviewPanel.addMngOptionDualSliders();
                        overviewPanel.createIndPanelLayouts();
                        overviewPanel.createIndSubPanels();
                        overviewPanel.addIndicatorGUIs();
                        overviewPanel.repaint();

                        //progressBar.setStatusLabelText("Drawing the Contour Plots");
                        cplomPanel.createLabels();
                        cplomPanel.createPlotPanels();
                        //cplomPanel.createCenterPanelLayout();
                        cplomPanel.addGUI();
                        cplomPanel.addPopupMenuItems();
                        cplomPanel.repaint();

                        //progressBar.setStatusLabelText("Creating the Trade-offs Panel");
                        tradeoffsPanel.addSortByIndComboBox();
                        tradeoffsPanel.setUncertaintyComboBoxSelected();
                        tradeoffsPanel.createIndicatorPlots();
                        tradeoffsPanel.addPlots();

                        optionsIndicatorsPanel.addIndicatorCheckBoxes();
                        tradeoffsIndicatorsPanel.addIndicatorCheckBoxes();

                        progressBar.close();
                    }
                };
                thread.start();
            }
        });
        openMenuItem.setAccelerator(KeyStroke.getKeyStroke('O', InputEvent.CTRL_DOWN_MASK));
        fileMenu.add(openMenuItem);

        openRecentDataMenuItem = new JMenuItem("Open Recent Data");
        openMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Open Recent Data menu item was pressed.");
            }
        });
        fileMenu.add(openRecentDataMenuItem);

        openProjectMenuItem = new JMenuItem("Open Project");
        openProjectMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Open Project menu item was pressed.");
            }
        });
        fileMenu.add(openProjectMenuItem);

        fileMenu.addSeparator();

        saveProjectMenuItem = new JMenuItem("Save Project");
        saveProjectMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Save Project menu item was pressed.");
            }
        });
        saveProjectMenuItem.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK));
        fileMenu.add(saveProjectMenuItem);

        saveProjectAsMenuItem = new JMenuItem("Save Project as");
        saveProjectAsMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Save Project As menu item was pressed.");
            }
        });
        saveProjectAsMenuItem.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK));
        fileMenu.add(saveProjectAsMenuItem);

        fileMenu.addSeparator();

        exportWinMenuItem = new JMenuItem("Export Windows to PNG");
        exportWinMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Export Windows to PNG menu item was pressed.");
            }
        });
        fileMenu.add(exportWinMenuItem);

        exportSceMenuItem = new JMenuItem("Export Scenarios to CSV");
        exportSceMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Export Scenarios to PNG menu item was pressed.");
            }
        });
        fileMenu.add(exportSceMenuItem);

        fileMenu.addSeparator();

        JMenuItem exitMenuItem = new JMenuItem("Exit");
        exitMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                close();
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);
    }

    private void addEditMenu(JMenuBar menuBar) {
        editMenu = new JMenu("Edit");

        JMenuItem undoMenuItem = new JMenuItem("Undo");
        undoMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Undo menu item was pressed.");
            }
        });
        undoMenuItem.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_DOWN_MASK));
        editMenu.add(undoMenuItem);

        editMenu.addSeparator();

        JMenuItem deleteAllSceMenuItem = new JMenuItem("Delete all Scenarios");
        deleteAllSceMenuItem.setIcon(new ImageIcon("images/delete.png"));
        deleteAllSceMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                scenariosPanel.removeAllScenarios();
            }
        });
        editMenu.add(deleteAllSceMenuItem);

        editMenu.addSeparator();

        JMenuItem preferencesMenuItem = new JMenuItem("Preferences");
        preferencesMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Preferences preferences = new Preferences();
                preferences.run();
            }
        });
        editMenu.add(preferencesMenuItem);

        menuBar.add(editMenu);
    }

    private void addWindowMenu(JMenuBar menuBar) {
        windowMenu = new JMenu("Window");

        overviewWinMenuItem = new JCheckBoxMenuItem("Constraint");
        overviewWinMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (overviewWinMenuItem.isSelected() &&
                    westToolWindowManager.getContentManager().getContentCount() == 0)
                    initWestToolWindowManager();
                overviewWinMenuItem.setSelected(overviewWinMenuItem.isSelected());
                setSubPanelVisibility();
            }
        });
        overviewWinMenuItem.setSelected(true);
        windowMenu.add(overviewWinMenuItem);

        cplomWinMenuItem = new JCheckBoxMenuItem("Contours");
        cplomWinMenuItem.setSelected(true);
        cplomWinMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (cplomWinMenuItem.isSelected() &&
                    eastToolWindowManager.getContentManager().getContentCount() == 0)
                    initEastToolWindowManager();
                cplomWinMenuItem.setSelected(cplomWinMenuItem.isSelected());
                setSubPanelVisibility();
            }
        });
        cplomWinMenuItem.setSelected(true);
        windowMenu.add(cplomWinMenuItem);

        tradeoffsWinMenuItem = new JCheckBoxMenuItem("Trade-offs");
        tradeoffsWinMenuItem.setSelected(true);
        tradeoffsWinMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (tradeoffsWinMenuItem.isSelected() &&
                    southToolWindowManager.getContentManager().getContentCount() == 0)
                    initSouthToolWindowManager();
                tradeoffsWinMenuItem.setSelected(tradeoffsWinMenuItem.isSelected());
                setSubPanelVisibility();
            }
        });
        tradeoffsWinMenuItem.setSelected(false);
        windowMenu.add(tradeoffsWinMenuItem);

        visualRefLineWinMenuItem = new JCheckBoxMenuItem("Visual Reference Lines");
        visualRefLineWinMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (visualRefLineWinMenuItem.isSelected()) {
                    visualRefLineDialog = new VisualRefLineDialog();
                    visualRefLineDialog.run();
                } else {
                    visualRefLineDialog.close();
                    visualRefLineDialog = null;
                }
            }
        });
        visualRefLineWinMenuItem.setSelected(false);
        windowMenu.add(visualRefLineWinMenuItem);

        menuBar.add(windowMenu);
    }

    private void addHelpMenu(JMenuBar menuBar) {
        helpMenu = new JMenu("Help");

        JMenuItem HelpMenuItem = new JMenuItem("Help");
        HelpMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Help menu item was pressed.");
            }
        });
        helpMenu.add(HelpMenuItem);

        JMenuItem aboutMenuItem = new JMenuItem("About");
        aboutMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("About menu item was pressed.");
            }
        });
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);
    }

    protected void initSplitPane() {
        splitHorizontal = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitHorizontal.setBorder(BorderFactory.createEmptyBorder());
        splitHorizontal.setOneTouchExpandable(false);
        splitHorizontal.setDividerSize(4);
        splitHorizontal.setContinuousLayout(true);
        splitHorizontal.setDividerLocation((int)(this.frame.getHeight() * 0.65));

        northPanel = new JPanel(new BorderLayout());
        splitHorizontal.setTopComponent(northPanel);

        southPanel = new JPanel(new BorderLayout());
        splitHorizontal.setBottomComponent(southPanel);

        Container frameContainer = this.frame.getContentPane();
        frameContainer.setLayout(new BorderLayout());
        frameContainer.add(splitHorizontal, BorderLayout.CENTER);

        splitVertical = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitVertical.setBorder(BorderFactory.createEmptyBorder());
        splitVertical.setOneTouchExpandable(false);
        splitVertical.setDividerSize(4);
        splitVertical.setContinuousLayout(true);
        splitVertical.setDividerLocation((int) (this.frame.getWidth() * 0.35));

        eastPanel = new JPanel(new BorderLayout());
        splitVertical.setRightComponent(eastPanel);

        westPanel = new JPanel(new BorderLayout());
        splitVertical.setLeftComponent(westPanel);
        northPanel.add(splitVertical, BorderLayout.CENTER);
    }

    protected void initWestToolWindowManager() {
        MyDoggyToolWindowManager myDoggyToolWindowManager = new MyDoggyToolWindowManager();
        this.westToolWindowManager = myDoggyToolWindowManager;

        initWestContentManager();

        westPanel.add(myDoggyToolWindowManager);
    }

    protected void initEastToolWindowManager() {
        MyDoggyToolWindowManager myDoggyToolWindowManager = new MyDoggyToolWindowManager();
        this.eastToolWindowManager = myDoggyToolWindowManager;

        // Register a Tool.

        eastToolWindowManager.registerToolWindow("Indicators",                      // Id
                                             "Indicators",                 // Title
                                             null,                         // Icon
                optionsIndicatorsPanel,    // Component
                                             ToolWindowAnchor.RIGHT);       // Anchor

        eastToolWindowManager.registerToolWindow("Options",                      // Id
                "Options",                 // Title
                null,                         // Icon
                optionsPanel,    // Component
                ToolWindowAnchor.RIGHT);       // Anchor

        setupEastTool();

        for (ToolWindow window : eastToolWindowManager.getToolWindows())
            window.setAvailable(true);

        initEastContentManager();

        eastPanel.add(myDoggyToolWindowManager);
    }

    protected void initSouthToolWindowManager() {
        MyDoggyToolWindowManager myDoggyToolWindowManager = new MyDoggyToolWindowManager();
        this.southToolWindowManager = myDoggyToolWindowManager;

        // Register a Tool.

        southToolWindowManager.registerToolWindow("Indicators",                      // Id
                                             "Indicators",                 // Title
                                             null,                         // Icon
                tradeoffsIndicatorsPanel,    // Component
                                             ToolWindowAnchor.RIGHT);       // Anchor

        southToolWindowManager.registerToolWindow("Scenarios",                      // Id
                                             "Scenarios",                 // Title
                                             null,                         // Icon
                                             scenariosPanel,    // Component
                                             ToolWindowAnchor.RIGHT);       // Anchor

        setupSouthTool();

        for (ToolWindow window : southToolWindowManager.getToolWindows())
            window.setAvailable(true);

        initSouthContentManager();

        southPanel.add(myDoggyToolWindowManager);
    }

    protected void setupEastTool() {
        ToolWindow optionsTool = eastToolWindowManager.getToolWindow("Options");
        toolWindowSetup(optionsTool);

        ToolWindow indTool = eastToolWindowManager.getToolWindow("Indicators");
        toolWindowSetup(indTool);

    }

    protected void setupSouthTool() {
        ToolWindow scenariosTool = southToolWindowManager.getToolWindow("Scenarios");
        toolWindowSetup(scenariosTool);

        ToolWindow indTool = southToolWindowManager.getToolWindow("Indicators");
        toolWindowSetup(indTool);
    }

    private void toolWindowSetup(ToolWindow toolWindow) {
        // RepresentativeAnchorDescriptor
        RepresentativeAnchorDescriptor representativeAnchorDescriptor = toolWindow.getRepresentativeAnchorDescriptor();
        representativeAnchorDescriptor.setPreviewEnabled(true);
        representativeAnchorDescriptor.setPreviewDelay(1500);
        representativeAnchorDescriptor.setPreviewTransparentRatio(0.4f);

        // DockedTypeDescriptor
        DockedTypeDescriptor dockedTypeDescriptor = (DockedTypeDescriptor) toolWindow.getTypeDescriptor(ToolWindowType.DOCKED);
        dockedTypeDescriptor.setDockLength(300);
        dockedTypeDescriptor.setPopupMenuEnabled(true);

        // SlidingTypeDescriptor
        SlidingTypeDescriptor slidingTypeDescriptor = (SlidingTypeDescriptor) toolWindow.getTypeDescriptor(ToolWindowType.SLIDING);
        slidingTypeDescriptor.setEnabled(false);

        // FloatingTypeDescriptor
        FloatingTypeDescriptor floatingTypeDescriptor = (FloatingTypeDescriptor) toolWindow.getTypeDescriptor(ToolWindowType.FLOATING);
        floatingTypeDescriptor.setEnabled(false);
    }

    protected void initWestContentManager() {
        ContentManager contentManager = westToolWindowManager.getContentManager();
        Content content = contentManager.addContent("Constraint",
                                                    "Constraint",
                                                    null,      // An icon
                                                    overviewPanel);
        content.setToolTipText("Constraint of Management Options and Indicators");

        setupWestContentManagerUI();
    }

    protected void initEastContentManager() {
        ContentManager contentManager = eastToolWindowManager.getContentManager();
        Content content = contentManager.addContent("Contours",
                                                    "Contours",
                                                    null,      // An icon
                                                    cplomPanel);
        content.setToolTipText("Contour Plot Matrix of Indicators");

        setupEastContentManagerUI();
    }

    protected void initSouthContentManager() {
        ContentManager contentManager = southToolWindowManager.getContentManager();
        Content content = contentManager.addContent("Trade-offs",
                                                    "Trade-offs",
                                                    null,      // An icon
                                                    tradeoffsPanel);
        content.setToolTipText("Trade-offs");
        setupSouthContentManagerUI();
    }

    protected void setupWestContentManagerUI() {

        TabbedContentManagerUI contentManagerUI = (TabbedContentManagerUI) westToolWindowManager.getContentManager().getContentManagerUI();

        contentManagerUI.setShowAlwaysTab(true);
        contentManagerUI.setTabPlacement(TabbedContentManagerUI.TabPlacement.TOP);
        contentManagerUI.addContentManagerUIListener(new ContentManagerUIListener() {
            public boolean contentUIRemoving(ContentManagerUIEvent event) {
                overviewWinMenuItem.setSelected(false);
                setSubPanelVisibility();
                return false;
            }

            public void contentUIDetached(ContentManagerUIEvent event) {
                splitVertical.setDividerLocation(0);
            }
        });

        TabbedContentUI contentUI = (TabbedContentUI) westToolWindowManager.getContentManager().getContent(0).getContentUI();

        contentUI.setCloseable(false);
        contentUI.setMaximizable(false);
        contentUI.setDetachable(true);
        contentUI.setMinimizable(false);
        contentUI.setTransparentMode(true);
        contentUI.setTransparentRatio(0.7f);
        contentUI.setTransparentDelay(1000);

        final Content content = westToolWindowManager.getContentManager().getContent(0);
        content.addPropertyChangeListener("detached", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
                if (propertyChangeEvent.getNewValue().equals(Boolean.TRUE)) {
                    Container container = content.getComponent().getParent();
                    while (!(container instanceof ContentDialog))
                        container = container.getParent();
                    ContentDialog dialog = (ContentDialog) container;
                    dialog.setLocation(0, 0);
                    dialog.setSize(Toolkit.getDefaultToolkit().getScreenSize());
                } else {
                    splitVertical.setDividerLocation((int) (frame.getWidth() * 0.35));
                }
            }
        });
    }

    protected void setupEastContentManagerUI() {

        TabbedContentManagerUI contentManagerUI = (TabbedContentManagerUI) eastToolWindowManager.getContentManager().getContentManagerUI();

        contentManagerUI.setShowAlwaysTab(true);
        contentManagerUI.setTabPlacement(TabbedContentManagerUI.TabPlacement.TOP);
        contentManagerUI.addContentManagerUIListener(new ContentManagerUIListener() {
            public boolean contentUIRemoving(ContentManagerUIEvent event) {
                cplomWinMenuItem.setSelected(false);
                setSubPanelVisibility();
                return false;
            }

            public void contentUIDetached(ContentManagerUIEvent event) {
                splitVertical.setDividerLocation(frame.getWidth());
            }
        });

        TabbedContentUI contentUI = (TabbedContentUI) eastToolWindowManager.getContentManager().getContent(0).getContentUI();

        contentUI.setCloseable(false);
        contentUI.setMaximizable(false);
        contentUI.setDetachable(true);
        contentUI.setMinimizable(false);
        contentUI.setTransparentMode(true);
        contentUI.setTransparentRatio(0.7f);
        contentUI.setTransparentDelay(1000);

        final Content content = eastToolWindowManager.getContentManager().getContent(0);
        content.addPropertyChangeListener("detached", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
                if (propertyChangeEvent.getNewValue().equals(Boolean.TRUE)) {
                    Container container = content.getComponent().getParent();
                    while (!(container instanceof ContentDialog))
                        container = container.getParent();
                    ContentDialog dialog = (ContentDialog) container;
                    dialog.setLocation(0, 0);
                    dialog.setSize(Toolkit.getDefaultToolkit().getScreenSize());
                } else {
                    splitVertical.setDividerLocation((int) (frame.getWidth() * 0.35));
                }
            }
        });
    }

    protected void setupSouthContentManagerUI() {
        TabbedContentManagerUI contentManagerUI = (TabbedContentManagerUI) southToolWindowManager.getContentManager().getContentManagerUI();

        contentManagerUI.setShowAlwaysTab(true);
        contentManagerUI.setTabPlacement(TabbedContentManagerUI.TabPlacement.TOP);
        contentManagerUI.addContentManagerUIListener(new ContentManagerUIListener() {
            public boolean contentUIRemoving(ContentManagerUIEvent event) {
                //splitHorizontal.setDividerLocation(frame.getHeight());
                tradeoffsWinMenuItem.setSelected(false);
                setSubPanelVisibility();
                return false;
            }

            public void contentUIDetached(ContentManagerUIEvent event) {
                splitHorizontal.setDividerLocation(frame.getHeight());
            }
        });

        TabbedContentUI contentUI = (TabbedContentUI) southToolWindowManager.getContentManager().getContent(0).getContentUI();

        contentUI.setCloseable(false);
        contentUI.setMaximizable(false);
        contentUI.setDetachable(true);
        contentUI.setMinimizable(false);
        contentUI.setTransparentMode(true);
        contentUI.setTransparentRatio(0.7f);
        contentUI.setTransparentDelay(1000);

        final Content content = southToolWindowManager.getContentManager().getContent(0);
        content.addPropertyChangeListener("detached", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
                if (propertyChangeEvent.getNewValue().equals(Boolean.TRUE)) {
                    Container container = content.getComponent().getParent();
                    while (!(container instanceof ContentDialog))
                        container = container.getParent();
                    //ContentDialog dialog = (ContentDialog) container;
                    tradeoffsContentDialog = (ContentDialog) container;
                    //tradeoffsContentDialog.setLocation(0, 0);
                    //tradeoffsContentDialog.setSize(Toolkit.getDefaultToolkit().getScreenSize());
                    tradeoffsContentDialog.setLocation(frame.getX(), frame.getY());
                    tradeoffsContentDialog.setSize(frame.getWidth(), frame.getHeight());
                } else {
                    splitHorizontal.setDividerLocation((int) (frame.getHeight() * 0.65));
                    tradeoffsContentDialog = null;
                }
                tradeoffsPanel.addPlots();
            }
        });
    }

    private void setSubPanelVisibility() {
        if (openMenuItem.isEnabled()) {         // before opening a file
            northPanel.setVisible(false);
            westPanel.setVisible(false);
            eastPanel.setVisible(false);
            southPanel.setVisible(false);
            return;
        }

        double verSplitPosition;
        double horSplitPosition;

        northPanel.setVisible(true);
        westPanel.setVisible(true);
        eastPanel.setVisible(true);
        southPanel.setVisible(true);

        if (overviewWinMenuItem.isSelected()) {
            if (cplomWinMenuItem.isSelected()) {
                if (tradeoffsWinMenuItem.isSelected()) {            // overview, cplom, trade-offs
                    verSplitPosition = 0.35;
                    horSplitPosition = 0.65;
                } else {                                            // overview, cplom
                    verSplitPosition = 0.35;
                    horSplitPosition = 1.0;

                    southPanel.setVisible(false);
                }
            } else {
                if (tradeoffsWinMenuItem.isSelected()) {            // overview, trade-offs
                    verSplitPosition = 1.0;
                    horSplitPosition = 0.65;

                    eastPanel.setVisible(false);
                } else {                                            // overview
                    verSplitPosition = 1.0;
                    horSplitPosition = 1.0;

                    eastPanel.setVisible(false);
                    southPanel.setVisible(false);
                }
            }
        } else {
            if (cplomWinMenuItem.isSelected()) {
                if (tradeoffsWinMenuItem.isSelected()) {            // cplom, trade-offs
                    verSplitPosition = 0.0;
                    horSplitPosition = 0.65;

                    westPanel.setVisible(false);
                } else {                                            // cplom
                    verSplitPosition = 0.0;
                    horSplitPosition = 1.0;

                    westPanel.setVisible(false);
                    southPanel.setVisible(false);
                }
            } else {
                if (tradeoffsWinMenuItem.isSelected()) {            // trade-offs
                    verSplitPosition = 1.0;
                    horSplitPosition = 0.0;

                    northPanel.setVisible(false);
                } else {                                            // none
                    verSplitPosition = 1.0;
                    horSplitPosition = 0.0;

                    northPanel.setVisible(false);
                    southPanel.setVisible(false);
                }
            }
        }

        splitVertical.setDividerLocation((int) (frame.getWidth() * verSplitPosition));
        splitHorizontal.setDividerLocation((int) (frame.getHeight() * horSplitPosition));
    }

    public void closeVisualRefLineDialog() {
        visualRefLineDialog.close();
        visualRefLineDialog = null;

        this.visualRefLineWinMenuItem.setSelected(false);
    }

    public void setPreferences() {
        System.out.println("preferences set!");
    }

    private static Vismon vismonInstance;

    public static Vismon getVismonInstance() {
        if (vismonInstance == null) {
            vismonInstance = new Vismon();
        }
        return vismonInstance;
    }

    public void haveScenarios(boolean have) {
        tradeoffsWinMenuItem.setSelected(have);
        setSubPanelVisibility();
    }

    public CplomPanel getCplomPanel() {
        return cplomPanel;
    }

    public OverviewPanel getOverviewPanel() {
        return overviewPanel;
    }

    public ScenariosPanel getScenarioPanel() {
        return scenariosPanel;
    }

    public TradeoffsPanel getTradeoffsPanel() {
        return tradeoffsPanel;
    }

    public IndicatorsPanel getTradeoffsIndicatorsPanel() {
        return tradeoffsIndicatorsPanel;
    }

    public void repaintCplomPanel() {
        cplomPanel.repaint();
        cplomPanel.repaintAllGUIs();
    }

    public void repaintOptionsPanel() {
        optionsPanel.repaint();
    }

    public void repaintOverviewPanel() {
        overviewPanel.repaint();
    }

    public void repaintTradeoffsPanel() {
        if (tradeoffsContentDialog == null) {
            southPanel.repaint();
        } else {
            tradeoffsContentDialog.repaint();
            if (tradeoffsPanel.needsRepaintingInMax()) {
                int width = tradeoffsContentDialog.getWidth();
                int height = tradeoffsContentDialog.getHeight();
                tradeoffsContentDialog.setSize(width-1, height);
                tradeoffsContentDialog.setSize(width, height);
            }
        }
    }

    public void setTradeoffsWinMenuItemSelected() {
        tradeoffsWinMenuItem.setSelected(true);
        setSubPanelVisibility();
    }

    public void updateIndicatorVisibility() {
        for (int rank = 0; rank < Session.getIndicatorNum(); ++rank) {
            boolean visible = Session.getIndicator(rank).isVisible();
            cplomPanel.setContourPlotVisible(rank, visible);
            cplomPanel.setPlotMenuItemVisible(rank, !visible);
            optionsIndicatorsPanel.setIndicatorCBoxSelected(rank, visible);
            optionsIndicatorsPanel.indicatorCBoxSelectedChanged();
            tradeoffsIndicatorsPanel.setIndicatorCBoxSelected(rank, visible);
            tradeoffsIndicatorsPanel.indicatorCBoxSelectedChanged();
        }
        cplomPanel.repaintPanelLayout();
        updatePlots();
    }

    public void addScatterPlot(ScatterPlot scatterPlot) {
        scatterPlotList.add(scatterPlot);
    }

    public void removeScatterPlot(ScatterPlot scatterPlot) {
        scatterPlotList.remove(scatterPlot);
    }

    public void updatePlots() {
        this.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        cplomPanel.repaintAllGUIs();
        overviewPanel.repaint();
        scenariosPanel.repaint();
        tradeoffsPanel.addPlots();
        southPanel.repaint();

        for (ScatterPlot sp : scatterPlotList)
            sp.repaint();
        this.frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }

    public static void main(String[] args) {
        System.out.println("Page " + (int)(Math.random() * 604));

        UIManager.put("swing.boldMetal", Boolean.FALSE);
        vismonInstance = new Vismon();
        try {
            vismonInstance.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
