/*
 * Licensed Materials - Property of Rogue Wave Software, Inc. 
 * © Copyright Rogue Wave Software, Inc. 2014, 2017 
 * © 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.
 */

package atc;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JTabbedPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;

import atc.simulation.Mobile;
import atc.simulation.SimulationContext;
import atc.simulation.SimulationController;
import ilog.views.IlvGrapher;
import ilog.views.IlvGraphic;
import ilog.views.IlvManager;
import ilog.views.IlvManagerLayer;
import ilog.views.IlvManagerView;
import ilog.views.IlvManagerViewInteractor;
import ilog.views.IlvPoint;
import ilog.views.IlvRect;
import ilog.views.IlvSelection;
import ilog.views.IlvSelectionFactory;
import ilog.views.beans.editor.IlvPointEditor;
import ilog.views.beans.editor.IlvRectEditor;
import ilog.views.event.InteractorChangedEvent;
import ilog.views.event.InteractorListener;
import ilog.views.graphic.composite.internal.IlvInvisibleSelection;
import ilog.views.maps.IlvAreaOfInterest;
import ilog.views.maps.IlvAreaOfInterestVector;
import ilog.views.maps.IlvAreasOfInterestProperty;
import ilog.views.maps.IlvCoordinate;
import ilog.views.maps.IlvCoordinateSystemProperty;
import ilog.views.maps.IlvMapInputStream;
import ilog.views.maps.IlvMapLayerTreeProperty;
import ilog.views.maps.IlvMapScaleLimiter;
import ilog.views.maps.beans.IlvJAreaOfInterestPanel;
import ilog.views.maps.beans.IlvJCompass;
import ilog.views.maps.beans.IlvJCoordinateSystemEditorPanel;
import ilog.views.maps.beans.IlvJMapsManagerViewControlBar;
import ilog.views.maps.beans.IlvJMouseCoordinateViewer;
import ilog.views.maps.beans.IlvLayerTree;
import ilog.views.maps.beans.IlvLayerTreePanel;
import ilog.views.maps.beans.IlvMapLayer;
import ilog.views.maps.beans.IlvMapLayerTreeModel;
import ilog.views.maps.datasource.IlvMapDataSource;
import ilog.views.maps.datasource.IlvMapDataSourceModel;
import ilog.views.maps.datasource.IlvMapDataSourceProperty;
import ilog.views.maps.format.IlvDefaultDataPathResolver;
import ilog.views.maps.format.IlvMapDataPathManager;
import ilog.views.maps.graphic.style.IlvMapStyle;
import ilog.views.maps.grids.IlvAbstractBaseGrid;
import ilog.views.maps.grids.IlvLatLonGrid;
import ilog.views.maps.grids.IlvMGRSGrid;
import ilog.views.maps.grids.IlvMGRSGridZone;
import ilog.views.maps.projection.IlvProjectionUtil;
import ilog.views.maps.raster.IlvRasterMappedBuffer;
import ilog.views.maps.raster.datasource.IlvRasterStyle;
import ilog.views.maps.raster.datasource.IlvTiledRasterDataSource;
import ilog.views.maps.srs.coordsys.IlvCoordinateSystem;
import ilog.views.maps.srs.coordsys.IlvGeographicCoordinateSystem;
import ilog.views.maps.srs.coordsys.IlvProjectedCoordinateSystem;
import ilog.views.maps.srs.coordtrans.IlvCoordinateTransformation;
import ilog.views.maps.srs.coordtrans.IlvCoordinateTransformationException;
import ilog.views.maps.theme.IlvMapStyleController;
import ilog.views.maps.theme.IlvMapStyleControllerProperty;
import ilog.views.swing.IlvJManagerViewControlBar;
import ilog.views.swing.IlvJManagerViewPanel;
import ilog.views.swing.IlvThreadedActivityMonitor;
import ilog.views.swing.IlvThreadedActivityMonitor.ActivityEvent;
import ilog.views.swing.IlvThreadedActivityMonitorProperty;
import ilog.views.swing.IlvToolTipManager;
import ilog.views.util.IlvImageUtil;
import ilog.views.util.IlvProductUtil;
import ilog.views.util.beans.IlvPropertyEditorManager;
import ilog.views.util.beans.editor.IlvStringArrayPropertyEditor;
import ilog.views.util.internal.IlvReflection;
import ilog.views.util.swing.layout.IlvBetterFlowLayout;

/**
 * This demo creates a simple map and overlays it with pure framework symbols.
 * Symbols are animated by a basic simulation engine.
 */
public class ATCDemo extends JRootPane {
  static {
    // Register property editor for some of the symbol properties.
    IlvPropertyEditorManager.registerEditor(IlvRect.class, IlvRectEditor.class);
    IlvPropertyEditorManager.registerEditor(IlvPoint.class, IlvPointEditor.class);
    IlvPropertyEditorManager.registerEditor(IlvReflection.arrayType(String.class), IlvStringArrayPropertyEditor.class);
  }

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

  /**
   * subclass of IlvSymbologyTreeView to provide symbol editing on a
   * double-click.
   */

  IlvManagerView view;// map view
  IlvJManagerViewPanel viewScroll;// scroll arond the map view
  JPanel symbologyPanel = new JPanel(new BorderLayout());
  IlvJCompass compass = new IlvJCompass();
  IlvJManagerViewControlBar viewToolbar; // zoom & selection toolbar
  IlvJAreaOfInterestPanel areaOfInterestPanel;// panel for areas of interest.
  IlvJCoordinateSystemEditorPanel csPanel;// coordinate system choice.
  IlvLayerTreePanel layerTreePanel;
  IlvJMouseCoordinateViewer locator;// coordinate information
  int frames;
  long lastTime;
  private JButton brightnessUpButton;
  private JButton brightnessDownButton;
  private JButton contrastUpButton;
  private JButton contrastDownButton;
  private JButton saturationUpButton;
  private JButton saturationDownButton;
  private JButton transparencyUpButton;
  private JButton transparencyDownButton;
  private JComboBox<String> gridCombo;
  private Timer t;
  private SimulationController simToolbar;

  private IlvManagerLayer gridLayer;


  /**
   * Constructor. creates and sets up the GUI.
   *
   */
  public ATCDemo() {
    super();
    // Make sure the swing construction is called in Swing event thread.
    ilog.views.util.swing.IlvSwingUtil.invokeAndWait(new Runnable() {
      Override
      public void run() {
        // create the main components
        view = new IlvManagerView() {
          Override
          public void paint(Graphics g) {
            super.paint(g);
            frames++;
          }
        };

        view.setManager(new IlvGrapher(0));
        IlvToolTipManager.registerView(view);

        viewScroll = new IlvJManagerViewPanel(view);
        viewToolbar = new IlvJMapsManagerViewControlBar();
        viewToolbar.setFloatable(false);

        areaOfInterestPanel = new IlvJAreaOfInterestPanel(view, true, false, false);
        csPanel = new IlvJCoordinateSystemEditorPanel();
        // Setup the components
        viewToolbar.setView(view);
        locator = new IlvJMouseCoordinateViewer();
        locator.setView(view);
        view.setKeepingAspectRatio(true);
        view.setBackground(new Color(60, 60, 80));
        view.setAntialiasing(true);
        view.setSize(new Dimension(600, 600));
        viewScroll.setPreferredSize(view.getSize());

        // geo reference the view
        view.getManager().setNamedProperty(new IlvCoordinateSystemProperty(IlvGeographicCoordinateSystem.WGS84));
        // setup coordinate system panel to reload symbols.
        csPanel.setCoordinateSystem(IlvCoordinateSystemProperty.GetCoordinateSystem(view.getManager()));
        csPanel.addCoordinateSystemChangeListener(new PropertyChangeListener() {
          Override
          public void propertyChange(PropertyChangeEvent evt) {
            IlvCoordinateSystem system = (IlvCoordinateSystem) evt.getNewValue();
            if (system instanceof IlvProjectedCoordinateSystem) {// JV-4401 -
                                                                 // change
                                                                 // center of
                                                                 // projection
                                                                 // to the
                                                                 // correct area
              IlvProjectedCoordinateSystem pcs = (IlvProjectedCoordinateSystem) system;
              boolean change = false;
              if (pcs.getProjection().getCentralMeridian() == 0) {
                pcs.getProjection().setCentralMeridian(SimulationContext.getCentralMeridian());
                change = true;
              }
              if (pcs.getProjection().getCentralParallel() == 0) {
                pcs.getProjection().setCentralParallel(SimulationContext.getCentralParallel());
                change = true;
              }
              if (change) {
                csPanel.setCoordinateSystem(pcs);
                return;
              }
            }
            view.getManager().setNamedProperty(new IlvCoordinateSystemProperty(system));

            // set coordinate transformation on context
            SimulationContext.setCoordinateTransformation(
                IlvCoordinateTransformation.CreateTransformation(IlvGeographicCoordinateSystem.KERNEL, system));

            // reload data using new projection
            try {
              reloadData();
            } catch (Exception e) {
              e.printStackTrace();
            }

            Mobile.projectionUpdated();

            // Zoom to area of interest
            IlvAreaOfInterest aoe = (IlvAreaOfInterest) areaOfInterestPanel.getList().getSelectedValue();
            if (aoe != null) {
              aoe.zoomTo(view);
            } else {
              SwingUtilities.invokeLater(new Runnable() {
                Override
                public void run() {
                  view.fitTransformerToContent();
                }
              });
            }
          }
        });
        /* show this symbology on the GUI */
        // add layer tree panel
        layerTreePanel = new IlvLayerTreePanel();
        layerTreePanel.setView(view);
        IlvLayerTree tree = layerTreePanel.getLayerTree();
        tree.setAllowDrag(false);
        // tree.setAllowRename(false);
        tree.setAllowDelete(false);
        tree.setShowAllLayersMenu(false);
        tree.setShowNewLayerMenu(false);
        tree.setShowHideLayerMenu(false);
        tree.setShowArrangeLayerMenu(false);
        tree.setShowRenameLayerMenu(false);
        tree.setShowDeleteLayerMenu(false);

        JToolBar imageToolbar = new JToolBar();
        imageToolbar.setFloatable(false);
        ActionListener BSCListener = new ActionListener() {
          Override
          public void actionPerformed(ActionEvent e) {
            JButton source = (JButton) e.getSource();
            applyImageBCS(source, 1.1f);
          }
        };
        try {
          brightnessUpButton = new JButton(
              new ImageIcon(IlvImageUtil.getImageFromFile(getClass(), "more_brightness.gif"))); //$NON-NLS-1$
          brightnessUpButton.setToolTipText("Increase overall brightness"); //$NON-NLS-1$
          brightnessUpButton.addActionListener(BSCListener);
          brightnessDownButton = new JButton(
              new ImageIcon(IlvImageUtil.getImageFromFile(getClass(), "less_brightness.gif"))); //$NON-NLS-1$
          brightnessDownButton.setToolTipText("Decrease overall brightness"); //$NON-NLS-1$
          brightnessDownButton.addActionListener(BSCListener);
          contrastUpButton = new JButton(new ImageIcon(IlvImageUtil.getImageFromFile(getClass(), "more_contrast.gif"))); //$NON-NLS-1$
          contrastUpButton.setToolTipText("Increase overall contrast"); //$NON-NLS-1$
          contrastUpButton.addActionListener(BSCListener);
          contrastDownButton = new JButton(
              new ImageIcon(IlvImageUtil.getImageFromFile(getClass(), "less_contrast.gif"))); //$NON-NLS-1$
          contrastDownButton.setToolTipText("Decrease overall contrast"); //$NON-NLS-1$
          contrastDownButton.addActionListener(BSCListener);
          saturationUpButton = new JButton(
              new ImageIcon(IlvImageUtil.getImageFromFile(getClass(), "more_saturation.gif"))); //$NON-NLS-1$
          saturationUpButton.setToolTipText("Increase overall saturation"); //$NON-NLS-1$
          saturationUpButton.addActionListener(BSCListener);
          saturationDownButton = new JButton(
              new ImageIcon(IlvImageUtil.getImageFromFile(getClass(), "less_saturation.gif"))); //$NON-NLS-1$
          saturationDownButton.setToolTipText("Decrease overall saturation"); //$NON-NLS-1$
          saturationDownButton.addActionListener(BSCListener);
          transparencyUpButton = new JButton(
              new ImageIcon(IlvImageUtil.getImageFromFile(getClass(), "more_transparency.gif"))); //$NON-NLS-1$
          transparencyUpButton.setToolTipText("Increase overall transparency"); //$NON-NLS-1$
          transparencyUpButton.addActionListener(BSCListener);
          transparencyDownButton = new JButton(
              new ImageIcon(IlvImageUtil.getImageFromFile(getClass(), "less_transparency.gif"))); //$NON-NLS-1$

          transparencyDownButton.setToolTipText("Decrease overall transparency"); //$NON-NLS-1$
          transparencyDownButton.addActionListener(BSCListener);
          Dimension buttonDim = new Dimension(26, 26);
          configureComponentSize(brightnessUpButton, buttonDim);
          configureComponentSize(brightnessDownButton, buttonDim);
          configureComponentSize(contrastUpButton, buttonDim);
          configureComponentSize(contrastDownButton, buttonDim);
          configureComponentSize(saturationUpButton, buttonDim);
          configureComponentSize(saturationDownButton, buttonDim);
          configureComponentSize(transparencyUpButton, buttonDim);
          configureComponentSize(transparencyDownButton, buttonDim);

          imageToolbar.add(brightnessUpButton);
          imageToolbar.add(brightnessDownButton);
          imageToolbar.add(contrastUpButton);
          imageToolbar.add(contrastDownButton);
          imageToolbar.add(saturationUpButton);
          imageToolbar.add(saturationDownButton);
          imageToolbar.add(transparencyUpButton);
          imageToolbar.add(transparencyDownButton);
        } catch (IOException e) {
          e.printStackTrace();
        }
        imageToolbar.addSeparator();
        JLabel gridLabel = new JLabel("Contextual grid "); //$NON-NLS-1$
        gridCombo = new JComboBox<String>(new String[] { "None", "Lat/Lon", "MGRS" }); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
        Dimension comboDim = new Dimension(70, 22);
        gridCombo.setPreferredSize(comboDim);
        gridCombo.setMinimumSize(comboDim);
        gridCombo.setMaximumSize(comboDim);
        imageToolbar.add(gridLabel);
        imageToolbar.add(gridCombo);
        gridCombo.addActionListener(new ActionListener() {
          Override
          public void actionPerformed(ActionEvent e) {
            int selectedIndex = gridCombo.getSelectedIndex();
            if (gridLayer != null) {
              view.getManager().removeLayer(gridLayer.getIndex(), false);
              gridLayer = null;
            }
            IlvAbstractBaseGrid grid;
            switch (selectedIndex) {
            case 1:
              grid = new IlvLatLonGrid();
              grid.setGridColor(Color.red);
              gridLayer = grid;
              view.getManager().addLayer(gridLayer, -1);
              view.setLayerCached(view.getManager().getLayersCount() - 1, true);
              break;
            case 2:
              grid = new IlvMGRSGrid();
              grid.setGridColor(Color.red);
              IlvMGRSGridZone.addAllZones((IlvMGRSGrid) grid);
              gridLayer = grid;
              view.getManager().addLayer(gridLayer, -1);
              view.setLayerCached(view.getManager().getLayersCount() - 1, true);
            }
            view.setOptimizedTranslation(selectedIndex == 0);
            view.repaint();
          }
        });

        // create the simulation controller GUI
        simToolbar = new SimulationController(view);
        simToolbar.setFloatable(false);

        // limit the zoom to correct scales.
        IlvMapScaleLimiter limiter = new IlvMapScaleLimiter(1f / 1000f, (float) (1 / 1E9));
        limiter.setView(view);

        IlvManager mgr = view.getManager();
        IlvThreadedActivityMonitor mon = IlvThreadedActivityMonitorProperty.GetThreadedActivityMonitor(mgr);
        // install an activityMonitor listener get setup simulation bounds when
        // GeoTIFF layer is done loading
        mon.addActivityListener(new IlvThreadedActivityMonitor.ActivityListener() {
          Override
          public void activityChanged(ActivityEvent e) {
            if (e.getEventType() == IlvThreadedActivityMonitor.ActivityEvent.ACTIVITY_REMOVED) {
              Object activity = e.getActivity();
              if (activity instanceof IlvTiledRasterDataSource) {
                if (((IlvTiledRasterDataSource) activity).getName().contains(".tif")) { //$NON-NLS-1$
                  // process with some simulation initialization
                  IlvManagerLayer mLayer = ((IlvTiledRasterDataSource) activity).getTiledLayer();
                  IlvRect bds = mLayer.computeBBox(null);
                  // use the geotiff area as simulation bounds
                  SimulationContext.setBounds(Math.toRadians(bds.getMinX()), -Math.toRadians(bds.getMaxY()),
                      Math.toRadians(bds.getMaxX()), -Math.toRadians(bds.getMinY()));
                }
              }
            }

          }
        });

        // load the map
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        loadInitialData();
        simToolbar.setSimulationLayerIndex(2);

        // initialize simulation parameters
        IlvMapLayerTreeModel ltm = IlvMapLayerTreeProperty.GetMapLayerTreeModel(view.getManager());
        Enumeration<?> e = ltm.getEnumeration();
        while (e.hasMoreElements()) {
          DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
          Object o = node.getUserObject();
          if (o instanceof IlvMapLayer) {
            IlvMapLayer layer = (IlvMapLayer) o;
            // IlvMapStyle style = layer.getStyle();
            if (layer.getName().contains("Simulation")) { //$NON-NLS-1$
              // insert empty manager layer for simulation
              IlvManagerLayer simLayer = new IlvManagerLayer();
              view.getManager().addLayer(simLayer, simToolbar.getSimulationLayerIndex());
              layer.insert(simLayer);
            } else if (layer.getName().contains("Clouds")) { //$NON-NLS-1$
              // cache this layer to improve performance
              view.setLayerCached(layer.getManagerLayer().getIndex(), true);
            }
          }
        }

        // set coordinate transformation
        IlvCoordinateSystem system = IlvCoordinateSystemProperty.GetCoordinateSystem(view.getManager());
        if (system != null) {
          SimulationContext.setCoordinateTransformation(
              IlvCoordinateTransformation.CreateTransformation(IlvGeographicCoordinateSystem.KERNEL, system));
        }
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

        // install invisible selection factory to prevent handle from appearing
        view.getManager().setSelectionFactory(new IlvSelectionFactory() {
          Override
          public IlvSelection makeSelection(IlvGraphic obj) {
            return new IlvInvisibleSelection(obj);
          }
        });

        // connect the dynamic theme controller to use the view scale as its
        // reference
        IlvMapStyleController themeControl = IlvMapStyleControllerProperty.GetMapStyleController(view.getManager());
        themeControl.setView(view);
        themeControl.updateCurrentTheme();
        IlvBetterFlowLayout layout = new IlvBetterFlowLayout(FlowLayout.LEADING);
        JPanel toolbarContainer = new JPanel(layout);
        // configure the main window
        getContentPane().add(toolbarContainer, BorderLayout.NORTH);
        toolbarContainer.add(viewToolbar);
        compass.setView(view);
        getContentPane().add(viewScroll, BorderLayout.CENTER);
        final JTabbedPane tabPane = new JTabbedPane();
        tabPane.addTab("Map layers", layerTreePanel); //$NON-NLS-1$
        tabPane.addTab("Areas of Interest", areaOfInterestPanel); //$NON-NLS-1$
        tabPane.addTab("Coordinate System", csPanel); //$NON-NLS-1$
        JPanel tabPanel = new JPanel(new BorderLayout());
        JPanel southPanel = new JPanel();
        southPanel.add(compass);
        southPanel.add(locator);
        tabPanel.add(southPanel, BorderLayout.SOUTH);
        tabPanel.add(tabPane, BorderLayout.CENTER);
        getContentPane().add(tabPanel, BorderLayout.LINE_START);
        final JLabel fpsLabel = new JLabel("FPS:100"); //$NON-NLS-1$
        simToolbar.addSeparator(new Dimension(10, 0));
        Dimension d = fpsLabel.getPreferredSize();
        d = new Dimension(50, (int) d.getHeight());
        fpsLabel.setMaximumSize(d);
        fpsLabel.setPreferredSize(d);
        fpsLabel.setMinimumSize(d);
        simToolbar.add(fpsLabel);
        toolbarContainer.add(simToolbar);
        toolbarContainer.add(imageToolbar);
        // Add a timer to compute and display the number of Frames(refresh) per
        // second.
        t = new Timer(true);
        t.schedule(new TimerTask() {
          Override
          public void run() {
            long time = System.currentTimeMillis();
            double fps = (1000 * frames) / (time - lastTime);
            frames = 0;
            lastTime = time;
            fpsLabel.setText("FPS:" + (int) fps); //$NON-NLS-1$
          }
        }, 1000, 1000);
        lastTime = System.currentTimeMillis();
      }
    });// event thread runnable
  }


  private void applyImageBCS(JButton source, float multiplier) {
    IlvMapLayerTreeModel ltm = IlvMapLayerTreeProperty.GetMapLayerTreeModel(view.getManager());
    Enumeration<?> e = ltm.getEnumeration();
    while (e.hasMoreElements()) {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
      Object o = node.getUserObject();
      if (o instanceof IlvMapLayer) {
        IlvMapLayer layer = (IlvMapLayer) o;
        IlvMapStyle style = layer.getStyle();
        if (layer.getName().contains("Symbol")) { //$NON-NLS-1$
          // skip symbol layer
          continue;
        }
        if (style != null) {
          if (source == transparencyUpButton) {
            style.setAlpha(style.getAlpha() / multiplier);
          } else if (source == transparencyDownButton) {
            style.setAlpha(Math.min(style.getAlpha() * multiplier, 1.0f));
          } else {
            if (style instanceof IlvRasterStyle) {
              IlvRasterStyle rasterStyle = (IlvRasterStyle) style;
              if (source == brightnessUpButton) {
                rasterStyle
                    .setBrightness(new Double(Math.min(rasterStyle.getBrightness().doubleValue() * multiplier, 2.0)));
              } else if (source == brightnessDownButton) {
                rasterStyle.setBrightness(new Double(rasterStyle.getBrightness().doubleValue() / multiplier));
              } else if (source == contrastUpButton) {
                rasterStyle
                    .setContrast(new Double(Math.min(rasterStyle.getContrast().doubleValue() * multiplier, 2.0)));
              } else if (source == contrastDownButton) {
                rasterStyle.setContrast(new Double(rasterStyle.getContrast().doubleValue() / multiplier));
              } else if (source == saturationUpButton) {
                rasterStyle
                    .setSaturation(new Double(Math.min(rasterStyle.getSaturation().doubleValue() * multiplier, 2.0)));
              } else if (source == saturationDownButton) {
                rasterStyle.setSaturation(new Double(rasterStyle.getSaturation().doubleValue() / multiplier));
              }
            }
          }
        }
      }
    }
    view.invalidateTripleBuffer(false);
    view.repaint();
  }

  /**
   * Loads a shape file.
   */
  private void loadInitialData() {
    URL mapFile = findURL("/data/Sf.ivl"); //$NON-NLS-1$

    try {
      String baseName = findURL("/data").toExternalForm(); //$NON-NLS-1$
      IlvDefaultDataPathResolver dpr = new IlvDefaultDataPathResolver(baseName);
      IlvMapDataPathManager.AddDataPathResolver(dpr);
      InputStream stream = new BufferedInputStream(mapFile.openStream());
      // Create map input stream
      IlvMapInputStream mapInput = new IlvMapInputStream(stream,
          (String) null /* imageFile.getFile() */);
      // Clear current manager
      final IlvManager manager = view.getManager();
      // Load the map
      mapInput.read(manager);
      // fit the view to its new content
      view.fitTransformerToContent(true);
    } catch (Exception e1) {
      e1.printStackTrace();
    }
  }

  /**
   *
   * @throws Exception
   */
  private void reloadData() throws Exception {
    IlvMapDataSourceModel dsm = IlvMapDataSourceProperty.GetMapDataSourceModel(view.getManager());
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) dsm.getRoot();
    int count = root.getChildCount();
    for (int i = 0; i < count; i++) {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(i);
      IlvMapDataSource source = (IlvMapDataSource) node.getUserObject();
      source.reset();
      source.start();
    }
    final IlvManager manager = view.getManager();
    SwingUtilities.invokeLater(new Runnable() {
      Override
      public void run() {
        IlvAreaOfInterestVector vector = IlvAreasOfInterestProperty.GetAreasOfInterest(manager);
        ((IlvAreaOfInterest) vector.get(0)).zoomTo(view);
      }
    });
  }

  /**
   * Main method
   *
   * @param args
   *          (ignored)
   */
  public static void main(String[] args) {
    // Sun recommends that to put the entire GUI initialization into the
    // AWT thread

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      Override
      public void run() {
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ATCDemo demo = new ATCDemo();
        frame.getContentPane().add(demo);
        frame.setTitle("Air traffic control demo"); //$NON-NLS-1$
        try {
          frame.setIconImage(IlvImageUtil.getImageFromFile(getClass(), "globe.gif")); //$NON-NLS-1$
        } catch (IOException e) {
          // do nothing
        }
        frame.pack();
        frame.setVisible(true);
      }
    });
  }

  /**
   * Looks for a resource in the classpath.
   * 
   * @param resource
   *          The resource to find.
   * @return The URL of the searched resource
   */
  public static URL findURL(String resource) {
    return ATCDemo.class.getResource(resource);
  }

  /**
   * Add an interactor on the toolbar.
   *
   * @param tooltip
   *          button tooltip.
   * @param imageURL
   *          url of button icon.
   * @param interactor
   *          interactor to install on button press.
   */
  protected void installInteractorButton(String tooltip, String imageURL, final IlvManagerViewInteractor interactor) {
    Image image = null;
    try {
      image = IlvImageUtil.getImageFromFile(ATCDemo.class, imageURL);
    } catch (IOException e1) {
      e1.printStackTrace();
    }
    final JToggleButton button = new JToggleButton(new ImageIcon(image));
    button.setMargin(new Insets(2, 2, 2, 2));
    if (tooltip != null)
      button.setToolTipText(tooltip);
    viewToolbar.add(button);
    button.addActionListener(new ActionListener() {
      Override
      public void actionPerformed(ActionEvent e) {
        if (button.isSelected()) {
          view.setInteractor(interactor);
          view.requestFocus();
        } else if (view.getInteractor() == interactor) {
          view.popInteractor();
        }
      }
    });
    InteractorListener interactorListener = new InteractorListener() {
      Override
      public void interactorChanged(InteractorChangedEvent event) {
        boolean isMyInteractor = (event.getNewValue() == interactor);
        if (button.isSelected() != isMyInteractor) {
          button.setSelected(isMyInteractor);
        }
      }
    };
    view.addInteractorListener(interactorListener);
  }

  /**
   * Computes the lat/lon of the point on the map.
   *
   * @param point
   *          location of the mouse on the view.
   * @return the lat/lon coordinates in radians, or null.
   */
  protected IlvCoordinate computeCoordinates(Point point) {
    IlvCoordinate coord;
    IlvPoint pt = new IlvPoint(point.x, point.y);
    view.getTransformer().inverse(pt);
    IlvProjectionUtil.invertY(pt);
    try {
      IlvCoordinateSystem cs = IlvCoordinateSystemProperty.GetCoordinateSystem(view.getManager());
      IlvCoordinateTransformation ct = IlvCoordinateTransformation.CreateTransformation(cs,
          IlvGeographicCoordinateSystem.KERNEL);
      coord = new IlvCoordinate(pt.x, pt.y);
      ct.transform(coord, coord);
    } catch (IlvCoordinateTransformationException e) {
      coord = null;
    }
    return coord;
  }

  private void configureComponentSize(JComponent comp, Dimension buttonDim) {
    comp.setPreferredSize(buttonDim);
    comp.setMinimumSize(buttonDim);
    comp.setMaximumSize(buttonDim);
  }

}