/*
 * 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.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.IlvHandlesSelection;
import ilog.views.IlvManagerView;
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.link.IlvLinkLayout;
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 link layout. It shows how to use link
 * layout in applications that are not based on CSS styling.
 */
public class LinkLayoutApp 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 view of the grapher */
  IlvManagerView mgrview = new IlvManagerView(grapher);

  /** An instance of the Link Layout algorithm */
  IlvLinkLayout layout = new IlvLinkLayout();

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

    // set some default values
    layout.setAutoLayout(true);

    // attach the grapher to the layout instances
    IlvGrapherAdapter adapter = new IlvGrapherAdapter(grapher);

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

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

    // use manager coordinates
    layout.setCoordinatesMode(IlvGraphLayout.MANAGER_COORDINATES);

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

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

    // modify the interactors such that the demo looks better
    IlvSelectInteractor selInter = ((IlvSelectInteractor) controlBar.getSelectInteractor());
    selInter.setOpaqueMove(true);
    selInter.setOpaqueResize(true);
    selInter.setOpaquePolyPointsEdition(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("sample1");
    fileSelector.addItem("sample2");
    fileSelector.addItem("sample2-spline");
    fileSelector.addItem("sample3");
    fileSelector.addItem("sample4");
    fileSelector.addItem("sample5");
    fileSelector.setToolTipText(getString("fileChooser.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, grapher);
      }
    });

    // create the panel for the layout buttons and parameters
    JPanel layoutPanel = new JPanel();
    layoutPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
    layoutPanel.add(layoutButton);
    addFurtherOptions(layoutPanel);

    // 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("fileChooser.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(layoutPanel, BorderLayout.NORTH);
    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("sample1");
  }

  /**
   * Fill the layout panel with further options.
   */
  private void addFurtherOptions(JPanel layoutPanel) {
    JPanel panel = new JPanel();
    layoutPanel.add(panel);
    panel.setLayout(new GridLayout(2, 1));

    JCheckBox longLinks = new JCheckBox(getString("longLinksCheckbox.Label"),
        (layout.getLayoutMode() == IlvLinkLayout.LONG_LINKS));
    longLinks.setToolTipText(getString("longLinksCheckbox.Tooltip"));
    panel.add(longLinks);
    longLinks.addItemListener(new ItemListener() {
      Override
      public void itemStateChanged(ItemEvent e) {
        setLayoutMode(e.getStateChange() == ItemEvent.SELECTED);
      }
    });

    JCheckBox orthoLinks = new JCheckBox(getString("orthoLinksCheckbox.Label"),
        (layout.getGlobalLinkStyle() == IlvLinkLayout.ORTHOGONAL_STYLE));
    orthoLinks.setToolTipText(getString("orthoLinksCheckbox.Tooltip"));
    panel.add(orthoLinks);
    orthoLinks.addItemListener(new ItemListener() {
      Override
      public void itemStateChanged(ItemEvent e) {
        setOrthLinkStyle(e.getStateChange() == ItemEvent.SELECTED);
      }
    });

    JCheckBox autoLayout = new JCheckBox(getString("autoLayoutCheckbox.Label"), layout.isAutoLayout());
    autoLayout.setToolTipText(getString("autoLayoutCheckbox.Tooltip"));
    layoutPanel.add(autoLayout);
    autoLayout.addItemListener(new ItemListener() {
      Override
      public void itemStateChanged(ItemEvent e) {
        setAutoLayout(e.getStateChange() == ItemEvent.SELECTED);
      }
    });
  }

  /**
   * Sets the layout mode.
   */
  private void setLayoutMode(boolean flag) {
    layout.setLayoutMode(flag ? IlvLinkLayout.LONG_LINKS : IlvLinkLayout.SHORT_LINKS);
  }

  /**
   * Sets the orithogonal link style or direct link style.
   */
  private void setOrthLinkStyle(boolean flag) {
    layout.setGlobalLinkStyle(flag ? IlvLinkLayout.ORTHOGONAL_STYLE : IlvLinkLayout.DIRECT_STYLE);
  }

  /**
   * Sets the orthogonal mode.
   */
  private void setAutoLayout(boolean flag) {
    layout.setAutoLayout(flag);
  }

  public void start() {
    // show all the graph
    mgrview.fitTransformerToContent();
  }

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

  /**
   * 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);
      // save the auto layout setting
      boolean autoLayoutFlag = layout.isAutoLayout();
      // don't lay out the grapher automatically after reading it
      // (this is just to allow the user to see the difference once
      // the layout is executed).
      layout.setAutoLayout(false);
      // empty the grapher
      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"));
      }
      // restore the previous state of the option
      layout.setAutoLayout(autoLayoutFlag);
      // show all the graph
      mgrview.fitTransformerToContent();
      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, LinkLayoutApp.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() {
        LinkLayoutApp app = new LinkLayoutApp();
        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);
      }
    });
  }

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

  /**
   * 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
   * orthogonal link 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. This method must be called before the layout is
     * started.
     */
    void initialize() {
      toShow = "";
    }
  }
}