/*
 * Licensed Materials - Property of Perforce Software, Inc. 
 * © Copyright Perforce Software, Inc. 2014, 2021 
 * © Copyright IBM Corp. 2009, 2014
 * © Copyright ILOG 1996, 2009
 * All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:
 * The Software and Documentation were developed at private expense and
 * are "Commercial Items" as that term is defined at 48 CFR 2.101,
 * consisting of "Commercial Computer Software" and
 * "Commercial Computer Software Documentation", as such terms are
 * used in 48 CFR 12.212 or 48 CFR 227.7202-1 through 227.7202-4,
 * as applicable.
 */

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.text.MessageFormat;
import java.util.Locale;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import ilog.views.IlvGrapher;
import ilog.views.IlvGraphic;
import ilog.views.IlvHandlesSelection;
import ilog.views.IlvLabelInterface;
import ilog.views.IlvManager;
import ilog.views.IlvManagerView;
import ilog.views.IlvTransformer;
import ilog.views.accelerator.IlvDeleteSelectionAccelerator;
import ilog.views.event.ManagerSelectionChangedEvent;
import ilog.views.event.ManagerSelectionListener;
import ilog.views.graphlayout.GraphLayoutEvent;
import ilog.views.graphlayout.GraphLayoutEventListener;
import ilog.views.graphlayout.IlvGraphLayout;
import ilog.views.graphlayout.IlvGraphLayoutException;
import ilog.views.graphlayout.IlvGraphLayoutReport;
import ilog.views.graphlayout.bus.IlvBusLayout;
import ilog.views.interactor.IlvSelectInteractor;
import ilog.views.interactor.IlvZoomViewInteractor;
import ilog.views.swing.IlvJManagerViewControlBar;
import ilog.views.swing.IlvJScrollManagerView;
import ilog.views.util.IlvLocaleUtil;
import ilog.views.util.IlvProductUtil;
import ilog.views.util.IlvResourceUtil;
import ilog.views.util.swing.IlvSwingUtil;

/**
 * This is a very simple application that uses the
 * <code>IlvGrapher</code> to perform a bus layout. It shows how to use bus
 * layout in applications that are not based on CSS styling.
 */
public class BusLayoutApp extends JRootPane implements ManagerSelectionListener {
  static {
    // Test code whether the demo works in RTL locales
    // Locale newLocale = new Locale("he");
    // IlvSwingUtil.setDefaultLocale(newLocale);
  }

  {
    // This sample uses JViews Diagrammer features. When deploying an
    // application that includes this code, you need to be in possession
    // of a JViews Diagrammer Deployment license.
    IlvProductUtil.DeploymentLicenseRequired(IlvProductUtil.JViews_Diagrammer_Deployment);
  }

  /** The grapher */
  IlvGrapher grapher = new IlvGrapher();

  /** The view of the grapher */
  IlvManagerView mgrview = new IlvManagerView(grapher);

  /** An instance of the Bus Layout algorithm */
  IlvBusLayout layout = new MyBusLayout();

  /** A graph layout event listener */
  LayoutIterationListener layoutListener = new LayoutIterationListener();

  /** A text field to display messages */
  JTextField msgLine = new JTextField();

  /**
   * Initializes the application.
   */
  public void init() {
    showMessage(getString("InitMessage"));

    // attach the grapher to the layout instance
    layout.attach(grapher);

    // specify the ordering option for the bus layout
    layout.setNodeComparator(IlvBusLayout.ASCENDING_INDEX);

    // specify the alignment option
    layout.setGlobalVerticalAlignment(IlvBusLayout.CENTER);

    // no need to pay the price of these checks in our case,
    // because we know the type of the links and the link connector
    // is appropriate for this layout
    layout.getGraphModel().setLinkCheckEnabled(false);
    layout.getGraphModel().setConnectionPointCheckEnabled(false);

    // install the layout iteration listener on the layout instance
    layout.addGraphLayoutEventListener(layoutListener);

    // create the scroll manager view
    IlvJScrollManagerView scrollManView = new IlvJScrollManagerView(mgrview);

    // allow the user to delete nodes by pressing the "del" key
    grapher.addAccelerator(new IlvDeleteSelectionAccelerator(KeyEvent.KEY_PRESSED, KeyEvent.VK_DELETE, 0));

    // listen the selection events
    grapher.addManagerSelectionListener(this);

    // Some settings on the manager view and on the scroll manager view
    mgrview.setAntialiasing(true);
    mgrview.setKeepingAspectRatio(true);
    mgrview.setBackground(Color.white);
    mgrview.setForeground(SystemColor.windowText);
    Color xc = SystemColor.windowText;
    xc = new Color(255 - xc.getRed(), 255 - xc.getGreen(), 255 - xc.getBlue());
    mgrview.setDefaultXORColor(xc);
    mgrview.setDefaultGhostColor(SystemColor.windowText);
    mgrview.setZoomFactorRange(0.02, 10.0);
    mgrview.setWheelZoomingEnabled(true);
    scrollManView.setWheelScrollingEnabled(true);

    // Settings parameters for selection handles
    IlvHandlesSelection.defaultHandleColor = Color.black;
    IlvHandlesSelection.defaultHandleBackgroundColor = Color.white;
    IlvHandlesSelection.defaultHandleShape = IlvHandlesSelection.SQUARE_SHAPE;

    // create the standard control bar
    IlvJManagerViewControlBar controlBar = new IlvJManagerViewControlBar();
    controlBar.setView(mgrview);

    // modify the interactors such that the demo looks better
    ((IlvSelectInteractor) controlBar.getSelectInteractor()).setOpaqueMove(true);
    ((IlvSelectInteractor) controlBar.getSelectInteractor()).setOpaqueResize(true);
    ((IlvZoomViewInteractor) controlBar.getZoomViewInteractor()).setPermanent(true);

    // set the initial interactor
    mgrview.setInteractor(controlBar.getSelectInteractor());

    // create the graph selector
    JComboBox<String> fileSelector = new JComboBox<String>();
    fileSelector.addItem("small");
    fileSelector.addItem("medium");
    fileSelector.addItem("large");
    fileSelector.setToolTipText(getString("fileSelector.Tooltip"));
    fileSelector.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent event) {
        SuppressWarnings("unchecked")
        JComboBox<String> comboBox = (JComboBox<String>) event.getSource();
        String fileName = (String) comboBox.getSelectedItem();
        loadGrapher(fileName);
      }
    });

    // create the layout button
    JButton layoutButton = new JButton(getString("layoutButton.Label"));
    layoutButton.setToolTipText(getString("layoutButton.Tooltip"));
    layoutButton.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent evt) {
        layout(layout);
      }
    });

    // create the panel for the layout buttons
    JPanel layoutButtonPanel = new JPanel();
    layoutButtonPanel.setLayout(new FlowLayout());
    layoutButtonPanel.add(layoutButton);
    addFurtherCheckboxes(layoutButtonPanel);

    // create the top panel with the toolbar and the file selector
    JPanel topPanel = new JPanel();
    topPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
    topPanel.add(controlBar);
    topPanel.add(new JLabel(getString("fileSelector.Label")));
    topPanel.add(fileSelector);

    // create the bottom panel with the layout buttons and the message line
    JPanel bottomPanel = new JPanel();
    bottomPanel.setLayout(new BorderLayout());
    bottomPanel.add(layoutButtonPanel, BorderLayout.NORTH);
    bottomPanel.add(createParameterPanel(), BorderLayout.CENTER);
    bottomPanel.add(msgLine, BorderLayout.SOUTH);
    msgLine.setEditable(false);

    // put manager view, top panel and bottom panel together
    getContentPane().setLayout(new BorderLayout(0, 0));
    getContentPane().add(scrollManView, BorderLayout.CENTER);
    getContentPane().add(topPanel, BorderLayout.NORTH);
    getContentPane().add(bottomPanel, BorderLayout.SOUTH);

    // set the component orientation according to the locale
    Locale loc = IlvSwingUtil.getDefaultLocale();
    ComponentOrientation co = ComponentOrientation.getOrientation(loc);
    getContentPane().applyComponentOrientation(co);

    // load a sample grapher
    loadGrapher("small");
  }

  /**
   * Adds further checkboxes near the layout button.
   */
  private void addFurtherCheckboxes(JPanel panel) {
    // some space
    panel.add(new JLabel("    "));

    JCheckBox incrementalOption = new JCheckBox(getString("incrementalMode.Checkbox.Label"), false);
    panel.add(incrementalOption);
    incrementalOption.setToolTipText(getString("incrementalMode.Checkbox.Tooltip"));
    incrementalOption.addItemListener(new ItemListener() {
      Override
      public void itemStateChanged(ItemEvent e) {
        layout.setIncrementalMode(e.getStateChange() == ItemEvent.SELECTED);
      }
    });

    JCheckBox preserveFixedNodesOption = new JCheckBox(getString("fixSelectedNodes.Checkbox.Label"), false);
    panel.add(preserveFixedNodesOption);
    preserveFixedNodesOption.setToolTipText(getString("fixSelectedNodes.Checkbox.Tooltip"));
    preserveFixedNodesOption.addItemListener(new ItemListener() {
      Override
      public void itemStateChanged(ItemEvent e) {
        layout.setPreserveFixedNodes(e.getStateChange() == ItemEvent.SELECTED);
      }
    });
  }

  /**
   * Creates the layout parameter panel.
   */
  private JPanel createParameterPanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(4, 2));

    // alignment paranter
    JComboBox<String> vAlignmentSelector = new JComboBox<String>();
    panel.add(new JLabel(getString("vAlignment.Label")));
    panel.add(vAlignmentSelector);
    vAlignmentSelector.setToolTipText(getString("vAlignment.Tooltip"));
    vAlignmentSelector.addItem(getString("vAlignment.CenterMode"));
    vAlignmentSelector.addItem(getString("vAlignment.TopMode"));
    vAlignmentSelector.addItem(getString("vAlignment.BottomMode"));
    vAlignmentSelector.setSelectedIndex(0);
    vAlignmentSelector.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent event) {
        SuppressWarnings("unchecked")
        JComboBox<String> comboBox = (JComboBox<String>) event.getSource();
        String alignment = (String) comboBox.getSelectedItem();
        setVerticalAlignment(alignment);
      }
    });

    // ordering of the nodes
    JComboBox<String> orderSelector = new JComboBox<String>();
    panel.add(new JLabel(getString("orderSelector.Label")));
    panel.add(orderSelector);
    orderSelector.setToolTipText(getString("orderSelector.Tooltip"));
    orderSelector.addItem(getString("orderSelector.NoneMode"));
    orderSelector.addItem(getString("orderSelector.AscLabelMode"));
    orderSelector.addItem(getString("orderSelector.DecLabelMode"));
    orderSelector.addItem(getString("orderSelector.AscWidthMode"));
    orderSelector.addItem(getString("orderSelector.DesWidthMode"));
    orderSelector.addItem(getString("orderSelector.AscHeightMode"));
    orderSelector.addItem(getString("orderSelector.DesHeightMode"));
    orderSelector.addItem(getString("orderSelector.AscAreaMode"));
    orderSelector.addItem(getString("orderSelector.DesAreaMode"));

    orderSelector.setSelectedIndex(1); // that is ascending label
    orderSelector.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent event) {
        SuppressWarnings("unchecked")
        JComboBox<String> comboBox = (JComboBox<String>) event.getSource();
        String ordering = (String) comboBox.getSelectedItem();
        setNodeComparator(ordering);
      }
    });

    // flow direction parameter
    JComboBox<String> flowDirectionSelector = new JComboBox<String>();
    panel.add(new JLabel(getString("flowDirectionSelector.Label")));
    panel.add(flowDirectionSelector);
    flowDirectionSelector.addItem(getString("flowDirectionSelector.LTRMode"));
    flowDirectionSelector.addItem(getString("flowDirectionSelector.AlternateMode"));
    flowDirectionSelector.setSelectedIndex(0);
    flowDirectionSelector.setToolTipText(getString("flowDirectionSelector.Tooltip"));
    flowDirectionSelector.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent event) {
        SuppressWarnings("unchecked")
        JComboBox<String> comboBox = (JComboBox<String>) event.getSource();
        String flow = (String) comboBox.getSelectedItem();
        setFlowDirection(flow);
      }
    });

    // node above/below bus parameter
    JComboBox<String> nodePositionSelector = new JComboBox<String>();
    panel.add(new JLabel(getString("nodePositionSelector.Label")));
    panel.add(nodePositionSelector);
    nodePositionSelector.addItem(getString("nodePositionSelector.AboveBusMode"));
    nodePositionSelector.addItem(getString("nodePositionSelector.BelowBusMode"));
    nodePositionSelector.setSelectedIndex(0);
    nodePositionSelector.setToolTipText(getString("nodePositionSelector.Tooltip"));
    nodePositionSelector.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent event) {
        SuppressWarnings("unchecked")
        JComboBox<String> comboBox = (JComboBox<String>) event.getSource();
        String position = (String) comboBox.getSelectedItem();
        setNodePosition(position);
      }
    });

    return panel;
  }

  /**
   * Sets the vertical node alignment.
   */
  private void setVerticalAlignment(String alignment) {
    if (alignment.equals(getString("vAlignment.CenterMode")))
      layout.setGlobalVerticalAlignment(IlvBusLayout.CENTER);
    else if (alignment.equals(getString("vAlignment.TopMode")))
      layout.setGlobalVerticalAlignment(IlvBusLayout.TOP);
    else if (alignment.equals(getString("vAlignment.BottomMode")))
      layout.setGlobalVerticalAlignment(IlvBusLayout.BOTTOM);
  }

  /**
   * Sets the node ordering mode.
   */
  private void setNodeComparator(String ordering) {
    if (ordering.equals(getString("orderSelector.NoneMode")))
      layout.setNodeComparator(null);
    else if (ordering.equals(getString("orderSelector.AscLabelMode")))
      layout.setNodeComparator(IlvBusLayout.ASCENDING_INDEX);
    else if (ordering.equals(getString("orderSelector.DecLabelMode")))
      layout.setNodeComparator(IlvBusLayout.DESCENDING_INDEX);
    else if (ordering.equals(getString("orderSelector.AscWidthMode")))
      layout.setNodeComparator(IlvBusLayout.ASCENDING_WIDTH);
    else if (ordering.equals(getString("orderSelector.DesWidthMode")))
      layout.setNodeComparator(IlvBusLayout.DESCENDING_WIDTH);
    else if (ordering.equals(getString("orderSelector.AscHeightMode")))
      layout.setNodeComparator(IlvBusLayout.ASCENDING_HEIGHT);
    else if (ordering.equals(getString("orderSelector.DesHeightMode")))
      layout.setNodeComparator(IlvBusLayout.DESCENDING_HEIGHT);
    else if (ordering.equals(getString("orderSelector.AscAreaMode")))
      layout.setNodeComparator(IlvBusLayout.ASCENDING_AREA);
    else if (ordering.equals(getString("orderSelector.DesAreaMode")))
      layout.setNodeComparator(IlvBusLayout.DESCENDING_AREA);
  }

  /**
   * Sets the flow direction of nodes.
   */
  private void setFlowDirection(String flow) {
    if (flow.equals(getString("flowDirectionSelector.LTRMode")))
      layout.setFlowDirection(IlvBusLayout.LEFT_TO_RIGHT);
    else if (flow.equals(getString("flowDirectionSelector.AlternateMode")))
      layout.setFlowDirection(IlvBusLayout.ALTERNATE);
  }

  /**
   * Sets the node position.
   */
  private void setNodePosition(String position) {
    if (position.equals(getString("nodePositionSelector.BelowBusMode")))
      layout.setNodePosition(IlvBusLayout.NODES_BELOW_BUS);
    else if (position.equals(getString("nodePositionSelector.AboveBusMode")))
      layout.setNodePosition(IlvBusLayout.NODES_ABOVE_BUS);
  }

  /**
   * Performs the layout of the graph.
   */
  private void layout(IlvGraphLayout layout) {
    // the layout report instance; this is an object in which
    // the layout algorithm stores information about its behavior
    IlvGraphLayoutReport layoutReport = null;

    showMessage(getString("LayoutStartMessage"));

    // initialize the iteration listener
    layoutListener.initialize();

    try {
      // perform the layout and get the layout report
      layoutReport = layout.performLayout(false, false);

      // print the code from the layout report
      showMessage(getString("LayoutDoneMessage"),
          layoutReport.codeToString(layoutReport.getCode(), IlvLocaleUtil.getCurrentULocale()));
    } catch (IlvGraphLayoutException e) {
      // e.printStackTrace();
      showMessage(e.getMessage());
    } finally {
      if (layoutReport != null && layoutReport.getCode() != IlvGraphLayoutReport.NOT_NEEDED) {
        // show all
        mgrview.repaint();
      }
    }
  }

  /**
   * Implementation of ilog.views.event.ManagerSelectionListener. It allows us
   * to change the "fixed" attribute of the nodes according to selection.
   * 
   * @param event
   *          the "selection changed" event.
   * @see IlvManager#addManagerSelectionListener
   * @see IlvManager#removeManagerSelectionListener
   * @see IlvManager#selectionChanged
   */
  Override
  public void selectionChanged(ManagerSelectionChangedEvent event) {
    IlvGraphic obj = event.getGraphic();
    if (grapher.isNode(obj))
      layout.setFixed(obj, grapher.isSelected(obj));
  }

  /**
   * Load a sample IVL file.
   * 
   * @param fileNameBase
   *          The base of the filename, excluding the path prefix and the
   *          extension suffix.
   */
  private void loadGrapher(String fileNameBase) {
    try {
      showMessage(getString("FileReadingStartMessage"), fileNameBase);
      grapher.deleteAll(false);
      grapher.read(IlvSwingUtil.getRelativeURL(this, "data/" + fileNameBase + ".ivl"));
      // the transformer may have been modified, so
      // we set the identity transformer
      mgrview.setTransformer(new IlvTransformer());
      grapher.reDraw();
      showMessage(getString("FileReadingDoneMessage"), fileNameBase);
    } catch (Exception e) {
      // e.printStackTrace();
      showMessage(e.getMessage());
    }
  }

  /**
   * Displays a message.
   */
  void showMessage(String message) {
    // the message is displayed in the message line
    msgLine.setText(message);
    msgLine.paintImmediately(0, 0, msgLine.getWidth(), msgLine.getHeight());
  }

  void showMessage(String msgformat, Object val) {
    Object[] args = { val };
    showMessage(MessageFormat.format(msgformat, args));
  }

  /**
   * Returns a string.
   */
  static String getString(String key) {
    return IlvResourceUtil.getString(key, BusLayoutApp.class, IlvLocaleUtil.getCurrentLocale());
  }

  /**
   * Allows you to run the demo as a standalone application.
   */
  public static void main(String[] arg) {
    // Sun recommends that to put the entire GUI initialization into the
    // AWT thread
    SwingUtilities.invokeLater(new Runnable() {
      Override
      public void run() {
        BusLayoutApp app = new BusLayoutApp();
        app.init();

        JFrame frame = new JFrame(getString("Frame.Label"));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 600);
        frame.getContentPane().add(app);
        frame.setVisible(true);
      }
    });
  }

  // -------------------------------------------------------------------------

  /**
   * A graph layout iteration listener. Implementing the interface
   * GraphLayoutEventListener gives you the possibility to receive during the
   * layout information about the behavior of the layout algorithm. This
   * information is contained in the graph layout event.
   * 
   * In our case, we will simply print a dot each time the method
   * layoutStepPerformed is called, that is after each iteration of the Bus
   * Layout algorithm.
   */
  class LayoutIterationListener implements GraphLayoutEventListener {
    private String toShow = "";
    private static final int MAX_LENGTH = 50;

    /**
     * This method is automatically called by the layout algorithm.
     */
    Override
    public void layoutStepPerformed(GraphLayoutEvent event) {
      // the status area has a limited width, so we are forced to
      // reinitialize the message string
      if (toShow.length() > MAX_LENGTH)
        toShow = "";

      toShow += ".";

      showMessage(toShow);
    }

    /**
     * Initialize the listener by reseting the toShow variable. This method must
     * be called before the layout is started.
     */
    void initialize() {
      toShow = "";
    }
  }
}

/**
 * A subclass of IlvBusLayout that overrides the method getIndex in order to
 * return the value of the label of the node. This allows the nodes to be order
 * in ascending order of their label. The same can be achieved using the method
 * setIndex, but this is less efficient.
 */
final class MyBusLayout extends IlvBusLayout {
  Override
  public int getIndex(Object node) {
    if (node instanceof IlvLabelInterface) {
      String label = ((IlvLabelInterface) node).getLabel();

      return Integer.valueOf(label).intValue();
    } else
      return 0;
  }
}