/*
 * Licensed Materials - Property of Rogue Wave Software, Inc. 
 * © Copyright Rogue Wave Software, Inc. 2014, 2015 
 * © 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 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.diagrammer.internal.AppletStringPropertyEditor;
import ilog.views.sdm.IlvSDMModel;
import ilog.views.util.IlvProductUtil;
import ilog.views.util.IlvResourceUtil;
import ilog.views.util.beans.IlvPropertyEditorManager;
import ilog.views.util.swing.IlvSwingUtil;

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.JApplet;
import javax.swing.JFrame;


/**
 * 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 JApplet{

    static {
        // This applet is designed to run only with default resource bundle
        // and various selected other resource bundles.
        // Setting the available resource suffixes avoids that the applet
        // tries to load resource bundles for other locales over the net,
        // even if the current locale of the browser is different.
        if (IlvResourceUtil.isInApplet())
            IlvResourceUtil.setAvailableResourceSuffixes("", "_ja");

        // This sample uses JViews Diagrammer features. When deploying an
        // application that includes this code, you need to be in possession
        // of a Rogue Wave 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";
    
    // a flag to indicate if the application is running as an applet
    private boolean isApplet = true;

    // 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 monitoringViews = new Hashtable();



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

    /**
     * Initializes the application/applet.
     */
  public void init() {
    IlvSwingUtil.invokeAndWait(new Runnable() { 
      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 {
      //    if( !isApplet) {
      //        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 either in the applet or in a frame
      if(isApplet) {
        getContentPane().add(dashboard);
      } else {
        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 {
            if (isApplet) {
                url = new URL(getDocumentBase(), path);
                IlvPropertyEditorManager.registerEditor(String.class, AppletStringPropertyEditor.class);
            } else {
                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/applet.
     */
    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(){

            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(){
            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"), new Integer(hh));
                clock.setParameterValue(clock.getParameter("minutes"), new Integer(mm));
                clock.setParameterValue(clock.getParameter("seconds"), new Integer(ss));
            }  
        };
        // creates and set the timer which perfom the task
        Timer timer = new Timer();
        timer.schedule(task,0,1000);
    }

    /**
     * Stops the applet.
     */
    public void stop() {
    }


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

}