/*
 * 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.Color;
import java.net.URL;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;
import javax.swing.JRootPane;

import ilog.views.dashboard.IlvDashboardContext;
import ilog.views.dashboard.IlvDashboardDiagram;
import ilog.views.dashboard.IlvDashboardInteractor;
import ilog.views.dashboard.IlvDashboardSymbol;
import ilog.views.diagrammer.IlvDiagrammerException;
import ilog.views.util.IlvProductUtil;
import ilog.views.util.swing.IlvSwingUtil;


/**
 * This is the entry point of the Tunnel demo.
 * It illustrates how to use dashboards and symbols to monitor traffic and events in a tunnel.
 * This demo simulates the traffic in a tunnel and several events which could affect either the 
 * traffic or the installations.
 * 
 */
public class Tunnel extends JRootPane {

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

  // the path to the idbd files (which defines the dashboards)
  private static final String mapPath = "data/tunnelMap.idbd";
  private static final String trafficPath = "data/tunnelDashboard.idbd";
  private static final String monitoringPath = "data/tunnelMonitoring.idbd";

  // the dashboard and context
  private IlvDashboardDiagram dashboard;
  private IlvDashboardContext context;

  // a reference to a symbol inside the dashboard: a clock that will be updated with current time
  private IlvDashboardSymbol clock = null;

  // storage for views corresponding to the two tunnels to monitor
  private Hashtable<String, MonitoringView> monitoringViews =
      new Hashtable<String, MonitoringView>();



  /**
   * Creates the demo
   */
  public Tunnel() {}

  /**
   * Initializes the application.
   */
  public void init() {
    IlvSwingUtil.invokeAndWait(new Runnable() {
      Override
      public void run() {
        createGUI();
      }
    });
  }

  public void createGUI() {

    // create the diagram and its context
    context = new IlvDashboardContext();
    dashboard = new IlvDashboardDiagram(context);

    // In application, we can load manually the palette.
    // Here this is useless because the palette is already in the CLASSPATH
    // E.g :
    // try {
    // context.loadPalettes(new URL("file:myPalette.jar"));
    // } catch (Exception e) {
    // System.err.println("Could not read the palette ");
    // System.exit(-1);
    // }

    // load the dashboard that will be the "menu" of the demo
    loadDashboard(dashboard, mapPath);
    // no need for scrollbars
    dashboard.setScrollable(false);
    dashboard.getView().setBackground(new Color(210, 210, 210));

    // display the dashboard in the a frame

    final JFrame frame = new JFrame();
    frame.setTitle("Tunnel Map");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.getContentPane().add(dashboard);
    frame.setBounds(0, 0, 730, 600);
    frame.setVisible(true);

    dashboard.fitToContents();
  }

  /**
   * Load a file into a dashboard component
   * 
   * @param dd The dashboard
   * @param path the .idbd file to load
   */
  private void loadDashboard(IlvDashboardDiagram dd, String path) {
    URL url = null;
    try {
      url = new URL("file:./" + path);
      dd.readDashboard(url);
    } catch (IlvDiagrammerException er) {
      er.getCause().printStackTrace();
      System.exit(-1);
    } catch (Exception e) {
      System.err.println("Could not read the file " + url);
      System.exit(-1);
    }
  }


  /**
   * Starts the application.
   */
  public void start() {

    // creates a new dashboard interactor and overrides the showDashboard method
    // in order to open the monitoring view corresponding to a freely defined url in the symbol
    IlvDashboardInteractor interactor = new IlvDashboardInteractor() {

      Override
      protected void showDashboard(String urlString) {
        // get the monitoring view associated with the url. In this case the url
        // is freely user defined: "Grant" or "Spring"
        MonitoringView mv = (MonitoringView) monitoringViews.get(urlString);

        // if no view has been created yet then creates it
        if (mv == null) {
          // creates and load the dashboards that will take place in the view
          IlvDashboardDiagram monitoringDashboard = new IlvDashboardDiagram(context);
          loadDashboard(monitoringDashboard, monitoringPath);
          IlvDashboardDiagram trafficDashboard = new IlvDashboardDiagram(context);
          loadDashboard(trafficDashboard, trafficPath);
          // creates the view with the dashboards and put it in the list of created views
          mv = new MonitoringView(urlString, monitoringDashboard, trafficDashboard);
          monitoringViews.put(urlString, mv);
        }

        // display the view and bring it to front
        mv.setVisible(true);
        mv.toFront();

      }
    };

    // set the new interactor on the dashboard
    dashboard.getView().setInteractor(interactor);

    // get a specific symbol of the dashboard in order to animate it later
    clock = dashboard.getSymbol("Clock_1");

    // creates a timer to update the clock in the dashboard
    // first we define a task that will be processed by the timer
    TimerTask task = new TimerTask() {
      Override
      public void run() {
        // get the time and extract hours, minutes and seconds
        Calendar now = Calendar.getInstance();
        int hh = now.get(Calendar.HOUR_OF_DAY);
        int mm = now.get(Calendar.MINUTE);
        int ss = now.get(Calendar.SECOND);

        // update the parameters of the clock
        clock.setParameterValue(clock.getParameter("hours"), Integer.valueOf(hh));
        clock.setParameterValue(clock.getParameter("minutes"), Integer.valueOf(mm));
        clock.setParameterValue(clock.getParameter("seconds"), Integer.valueOf(ss));
      }
    };
    // creates and set the timer which perfom the task
    Timer timer = new Timer();
    timer.schedule(task, 0, 1000);
  }

  /**
   * Entry point: loads the dashboard and display it
   * @param args (unused)
   */
  public static void main(String[] args) {
    IlvSwingUtil.invokeAndWait(new Runnable() {
      Override
      public void run() {
        Tunnel dashboard = new Tunnel();
        dashboard.init();
        dashboard.start();
      }
    });
  }

}