/*
 * 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.IlvHandlesSelection;
import ilog.views.IlvManagerView;
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.random.IlvRandomLayout;
import ilog.views.graphlayout.uniformlengthedges.IlvUniformLengthEdgesLayout;
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 shows how to use the
 * stopImmediate method to stop a running layout. This is a multi threaded
 * version. The app allows to randomize the graph, stop start layout or to
 * stop layout. The layout is animated. This app is not based on CSS styling.
 */
public class StopLayoutApp 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 Uniform Length Edges Layout algorithm */
  IlvUniformLengthEdgesLayout layout = new IlvUniformLengthEdgesLayout();

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

  /** Whether the app is busy */
  boolean busy = false;

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

  /** The chooses for file and layout style */
  JComboBox<String> fileChooser = new JComboBox<String>();

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

  /** The buttons */
  JButton randomButton = new JButton(getString("RandomizeButton.Label"));
  JButton layoutButton = new JButton(getString("StartLayoutButton.Label"));
  JButton stopButton = new JButton(getString("StopLayoutButton.Label"));

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

    JPanel panel;
  
    // attach the grapher to the layout instances
    IlvGrapherAdapter adapter = new IlvGrapherAdapter(grapher);
    adapter.setAnimationRedrawMode(IlvManagerView.THREADED_REDRAW);
    layout.attach(adapter);
    randomLayout.attach(adapter);

    // Because the nodes can have different sizes, ask the Uniform Length Edges
    // layout to take into account the size of each node
    layout.setRespectNodeSizes(true);

    // many iterations
    layout.setAllowedNumberOfIterations(100000);

    // animation should be on
    layout.setAnimate(true);

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

    // use manager coordinates
    layout.setCoordinatesMode(IlvGraphLayout.MANAGER_COORDINATES);
    randomLayout.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.003, 10.0);

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

    // graph selection
    panel.add(new JLabel(getString("fileChooser.Label")));
    panel.add(fileChooser);
    fileChooser.addItem("demo1");
    fileChooser.addItem("demo2");
    fileChooser.setToolTipText(getString("fileChooser.Tooltip"));
    fileChooser.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent event) {
        if (busy) {
          showMessage(getString("AnimRunningMessage"));
          return;
        }
        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);

    // the panel with the buttons
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
    buttonPanel.add(randomButton);
    buttonPanel.add(layoutButton);
    buttonPanel.add(stopButton);
    bottomPanel.add("North", buttonPanel);

    randomButton.setToolTipText(getString("RandomizeButton.Tooltip"));
    randomButton.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent e) {
        if (busy) {
          showMessage(getString("LayoutRunningMessage"));
          return;
        }
        Thread layoutThread = new Thread(new GraphLayoutPerformer(StopLayoutApp.this, randomLayout, grapher));
        layoutThread.start();
      }
    });

    layoutButton.setToolTipText(getString("StartLayoutButton.Tooltip"));
    layoutButton.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent e) {
        if (busy) {
          showMessage(getString("LayoutRunningMessage"));
          return;
        }
        Thread layoutThread = new Thread(new GraphLayoutPerformer(StopLayoutApp.this, layout, grapher));
        layoutThread.start();
      }
    });

    stopButton.setToolTipText(getString("StopLayoutButton.Tooltip"));
    stopButton.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent e) {
        if (busy)
          showMessage(getString("LayoutStoppedMessage"));
        else
          showMessage(getString("NoStopMessage"));
        layout.stopImmediately();
      }
    });

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

    // wait for the users input
    busy = false;
  }

  /**
   * 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() {
        StopLayoutApp app = new StopLayoutApp();
        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"));
      }
      // 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.
   */
  synchronized void showMessage(String message) {
    // the message is displayed in the message line
    msgLine.setText(message);
  }

  synchronized 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, StopLayoutApp.class, IlvLocaleUtil.getCurrentLocale());
  }
}

// ----------------------------------------------------------------------------
// The GraphLayoutPerformer, a Runnable that performs the layout.

class GraphLayoutPerformer implements Runnable {
  StopLayoutApp app;
  IlvGraphLayout layout;
  IlvGrapher grapher;

  GraphLayoutPerformer(StopLayoutApp app, IlvGraphLayout layout, IlvGrapher grapher) {
    this.app = app;
    this.layout = layout;
    this.grapher = grapher;
  }

  Override
  public void run() {
    // and mark the app as busy to prevent further input
    app.busy = true;

    // show a start message
    app.showMessage(StopLayoutApp.getString("LayoutStartMessage"));

    // sleep to get the awt thread the opportunity to draw the message
    try {
      Thread.sleep(20);
    } catch (InterruptedException e) {
    }

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

      if (layoutReport.getCode() == IlvGraphLayoutReport.LAYOUT_DONE) {
        app.showMessage(StopLayoutApp.getString("LayoutReallyDoneMessage"));
        app.mgrview.fitTransformerToContent();
      } else {
        app.showMessage(StopLayoutApp.getString("LayoutDoneMessage"),
            layoutReport.codeToString(layoutReport.getCode(), IlvLocaleUtil.getCurrentULocale()));
      }

      grapher.reDraw();
    } catch (IlvGraphLayoutException e) {
      // e.printStackTrace();
      app.showMessage(e.getMessage());
    } finally {
      // mark the app as not busy anymore
      app.busy = false;
    }
  }
}

// ----------------------------------------------------------------------------
// The Layout Iteration Listener.

/**
 * 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 sleep a short while each time the method
 * layoutStepPerformed is called, that is after each iteration of the layout
 * algorithm. This is important because it gives the other threads the
 * opportunity to perform their tasks. We will also print a dot each time the
 * method layoutStepPerformed is called.
 */
class GraphLayoutIterationListener implements GraphLayoutEventListener {
  private String toShow = "";
  private StopLayoutApp app;
  private static final int MAX_LENGTH = 50;

  GraphLayoutIterationListener(StopLayoutApp app) {
    this.app = app;
  }

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

    app.showMessage(toShow);

    // sleep to get the paint thread the opportunity to work
    try {
      Thread.sleep(100);
    } catch (InterruptedException e) {
    }
  }

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