/*
 * 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.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.MessageFormat;
import java.util.Locale;

import javax.swing.JButton;
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.IlvGraphicEnumeration;
import ilog.views.IlvHandlesSelection;
import ilog.views.IlvManagerView;
import ilog.views.IlvPoint;
import ilog.views.IlvTransformer;
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.IlvGrapherAdapter;
import ilog.views.graphlayout.circular.IlvCircularLayout;
import ilog.views.graphlayout.circular.IlvClusterId;
import ilog.views.graphlayout.circular.IlvClusterInfoProperty;
import ilog.views.graphlayout.random.IlvRandomLayout;
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 circular layout. It shows how to use
 * circular layout in applications that are not based on CSS styling.
 */
public class CircularLayoutApp extends JRootPane {
  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 grapher adapter for layout */
  IlvGrapherAdapter adapter = new IlvGrapherAdapter(grapher);

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

  /** An instance of the Circular Layout algorithm. */
  IlvCircularLayout layout = new IlvCircularLayout();

  /** An instance of the Random Layout algorithm */
  IlvRandomLayout randomLayout = new IlvRandomLayout();

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

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

  private static final boolean FIT_AFTER_LOAD = true;
  private static final boolean FIT_AFTER_LAYOUT = true;

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

    JPanel panel;
    
    // attach the grapher to the layout instances
    layout.attach(adapter);
    randomLayout.attach(adapter);

    // a few layout parameters
    layout.setConnectLinksToNodeCenters(true);
    layout.setMultiLinkMode(IlvCircularLayout.NARROW_STRAIGHT_LINE_BUNDLE);
    layout.setSelfLinkMode(IlvCircularLayout.NARROW_CONNECTED_SQUARE);
    layout.setSelfLinkRelativeAttachPosition(new IlvPoint(0.5, 0.5));
    layout.setSelfLinkSpacing(-1);

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

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

    // 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;

    // set the layout manager
    getContentPane().setLayout(new BorderLayout(0, 0));

    // fit so far all together
    getContentPane().add("Center", scrollManView);
    getContentPane().add("North", panel = new JPanel());
    panel.setLayout(new FlowLayout(FlowLayout.LEADING));

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

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

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

    // create the graph selector
    panel.add(new JLabel(getString("fileChooser.Label")));
    JComboBox<String> chooser;
    panel.add(chooser = new JComboBox<String>());
    chooser.addItem("small");
    chooser.addItem("medium");
    chooser.addItem("large");
    chooser.addItem("huge");
    chooser.addItem("subgraphs1");
    chooser.addItem("subgraphs2");
    chooser.setToolTipText(getString("fileChooser.Tooltip"));
    chooser.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 panel on bottom
    JPanel bottomPanel = new JPanel();
    bottomPanel.setLayout(new BorderLayout());
    getContentPane().add("South", bottomPanel);

    // create the layout buttons
    JButton b;
    JPanel layoutPanel = new JPanel();
    bottomPanel.add("North", layoutPanel);
    layoutPanel.add(b = new JButton(getString("RandomizeButton.Label")));
    b.setToolTipText(getString("RandomizeButton.Tooltip"));
    b.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent evt) {
        layout(randomLayout, grapher);
      }
    });

    layoutPanel.add(b = new JButton(getString("LayoutButton.Label")));
    b.setToolTipText(getString("LayoutButton.Tooltip"));
    b.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent evt) {
        setClusterMembershipInfo(layout, grapher);
        layout(layout, grapher);
      }
    });

    // add the message line to the bottom panel
    bottomPanel.add("South", msgLine);
    msgLine.setEditable(false);

    // 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");
  }

  /**
   * 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() {
        CircularLayoutApp app = new CircularLayoutApp();
        app.init();

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

  /**
   * 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);

      try {
        grapher.read(IlvSwingUtil.getRelativeURL(this, "data/" + fileNameBase + ".ivl"));
      } catch (Exception ex1) {
        // This case occurs only when we pack the entire application into
        // one jar including the data files, and start as application
        grapher.read(getClass().getResource("data/" + fileNameBase + ".ivl"));
      }

      if (FIT_AFTER_LOAD)
        // show all
        mgrview.fitTransformerToContent();
      else
        // the transformer may have been modified, so
        // we set the identity transformer
        mgrview.setTransformer(new IlvTransformer());

      if (fileNameBase.startsWith("subgraphs"))
        // the sample don't contain clustering information. The clustering
        // is done automatically by the Circular layout on the basis of
        // the nested graph structure stored in the IVL file.
        layout.setClusteringMode(IlvCircularLayout.BY_SUBGRAPHS);
      else
        // the sample contains clustering information. The clustering
        // is done automatically by the Circular layout on the basis of
        // the cluster information stored in the IVL file.
        layout.setClusteringMode(IlvCircularLayout.BY_CLUSTER_IDS);

      if (fileNameBase.startsWith("huge")) {
        layout.setMultiLinkMode(IlvCircularLayout.FREE_ONE_BEND_BUNDLE);
        layout.setMultiLinkOffset(20);
        layout.setMultiLinkMaxSpread(100);
        layout.setSelfLinkMode(IlvCircularLayout.NARROW_CONNECTED_RECTANGULAR);
        layout.setSelfLinkSpacing(10);
      } else {
        layout.setMultiLinkMode(IlvCircularLayout.NARROW_STRAIGHT_LINE_BUNDLE);
        layout.setMultiLinkOffset(10);
        layout.setMultiLinkMaxSpread(50);
        layout.setSelfLinkMode(IlvCircularLayout.NARROW_CONNECTED_SQUARE);
        layout.setSelfLinkSpacing(-1);
      }

      grapher.reDraw();
      showMessage(getString("FileReadingDoneMessage"), fileNameBase);
    } catch (Exception e) {
      // e.printStackTrace();
      showMessage(e.getMessage());
    }
  }

  /**
   * Loads membership information.
   */
  private void setClusterMembershipInfo(IlvCircularLayout layout, IlvGrapher grapher) {
    // The Circular Layout algorithm uses membership information to
    // build the clusterization of the graph. In other words, it needs
    // to know to which cluster each node belongs. It needs also to
    // know the order of the nodes on the cluster.
    // This information is specified to the layout algorithm using the
    // methods IlvCircularLayout.addClusterId and IlvCircularLayout.setClusterId
    // To obtain the persistence of this information, it was stored in the
    // nodes using a subclass of IlvNamedProperties provided in the
    // package ilog.views.graphlayout.circular: IlvClusterInfoProperty.
    // The sample ivl files contain such information, that must be read and
    // transfered to the layout instance.

    IlvGraphicEnumeration e = grapher.getObjects();
    // browse all the nodes of the grapher
    while (e.hasMoreElements()) {
      IlvGraphic obj = e.nextElement();
      // skip links
      if (!grapher.isNode(obj))
        continue;

      int count = layout.getClusterIdsCount(obj);

      // skip nodes for which cluster membership information
      // was already specified to the layout algorithm
      if (count > 0)
        continue;

      IlvClusterInfoProperty clusterIdsProp = (IlvClusterInfoProperty) obj
          .getNamedProperty(IlvClusterInfoProperty.NAME);

      // skip nodes for which no cluster membership information
      // was stored in the ivl file using named properties
      if (clusterIdsProp == null)
        continue;

      IlvClusterId[] clusterIds = clusterIdsProp.getClusterIds();
      int[] indexes = clusterIdsProp.getIndexes();

      for (int i = 0; i < clusterIds.length; i++) {
        int index = indexes[i];
        if (index >= 0)
          layout.addClusterId(obj, clusterIds[i], index);
        else
          // if index < 0, this means that the node has no index specification
          layout.addClusterId(obj, clusterIds[i]);
      }

      // specify the star center attribute
      layout.setStarCenter(obj, clusterIdsProp.isStarCenter());
    }
  }

  /**
   * Performs the layout of the graph.
   */
  private void layout(IlvGraphLayout layout, IlvGrapher grapher) {
    // 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
    // (this will simply empty the message string)
    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) {
        if (FIT_AFTER_LAYOUT)
          // show all
          mgrview.fitTransformerToContent();

        grapher.reDraw();
      }
    }
  }

  /**
   * 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, CircularLayoutApp.class, IlvLocaleUtil.getCurrentLocale());
  }

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

  /**
   * 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 = "";
    }
  }
}