// $Id: Main.java,v 1.9 2004/10/15 19:16:08 caron Exp $
/*
 * Copyright 1997-2002 Unidata Program Center/University Corporation for
 * Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
 * support@unidata.ucar.edu.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at
 * your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package thredds.viewer;

import thredds.ui.BAMutil;
import thredds.ui.TopLevel;
import thredds.util.*;

import ucar.util.prefs.*;
import ucar.util.prefs.ui.Debug;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;


 /**
 * The "TopLevel" object for THREDDS Data Viewer
 * that allows to run as an Applet or an Application.
 *
 * @author John Caron
 * @version $Id: Main.java,v 1.9 2004/10/15 19:16:08 caron Exp $
 */
public class Main extends JApplet implements TopLevel {
  private static boolean debug = true;

  //////////////// applet code
  private Common common;
  public void init() {
    if (debug) System.out.println("Applet::init()");
    common = new Common(this, this, true);
    validate();
  }
  public void destroy() { if (debug) System.out.println("Applet::destroy()"); }
  public void start() {if (debug) System.out.println("Applet::start() new"); }
  public void stop() { if (debug) System.out.println("Applet::stop()");
    // content.save();  dont bother till we figure out Security
  }

  // TopLevel methods
  public RootPaneContainer getRootPaneContainer() { return this; }
  public javax.swing.JFrame getJFrame() { return null; }

  public boolean isApplet() { return true; }
  public void close() {
    stop();
    destroy();
  }
  public void save() {
    // content.save();  dont bother till we figure out Security
  }

  ////////////////// application code
  public static void main(String[] args) {
    // handle multiple versions of TDV running
    if (args.length > 0) {
      StringBuffer sbuff = new StringBuffer();
      for (int i=0; i<args.length; i++) {
        sbuff.append(args[i]);
        sbuff.append(" ");
      }
      System.out.println(" main args == "+sbuff);
      // see if another version is running
      SocketMessage sm = new SocketMessage( 4444, sbuff.toString());
      if (sm.isAlreadyRunning()) {
        System.out.println("TDV already running - pass args to it= '"+sbuff+
                           "'\n and exit");
        System.exit(0);
      }
    } else
      System.out.println(" main no args");

    // otherwise start it up
    TopLevelJFrame top_jf = new TopLevelJFrame();
  }

  private static class TopLevelJFrame implements TopLevel {
    JFrame top;
    Common common;

    TopLevelJFrame() {
        // the top - level frame
      top = new JFrame("THREDDS Toolset");
        // catch window exit
      top.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent event) { close(); }
      });
      top.setIconImage( BAMutil.getImage( "GDVs"));

        // construct GUI here
      common = new Common(top, this, false);
      top.pack();
      top.setVisible(true);

    }
    public RootPaneContainer getRootPaneContainer() { return top; }
    public javax.swing.JFrame getJFrame() { return top; }

    public boolean isApplet() { return false; }
    public void close() {
      save();
      System.exit(0);
    }
    public void save() {
      common.saveConfig();
    }
  }

  /////////////// common code for apps and applets
  private static class Common {
    private XMLStore xstore = null;
    private String storeFilename = null;
    private PreferencesExt store;
    private UI ui;
    private Component mainC;

    Common(Component mainC, TopLevel topLevel, boolean isApplet) {
      this.mainC= mainC;

      // open up the preferences file(s)
      XMLStore sys = null;
      try {
        sys = XMLStore.createFromResource("/resources/config/ThreddsDataViewer.xml", null);
      } catch (java.io.IOException e) {
        System.out.println("Cant open XMLStore system default file");
      }
      try {
        storeFilename = XMLStore.makeStandardFilename(".unidata", "ThreddsDataViewer.xml");
        xstore = XMLStore.createFromFile(storeFilename, sys);
      } catch (java.io.IOException e) {
        System.out.println("Cant open XMLStore "+storeFilename);
        e.printStackTrace();
      }
      store = xstore.getPreferences();
      Debug.setStore( store.node("Debug"));

      if (Debug.isSet("util/showProperties")) {
        try {
          Properties p = System.getProperties();
          Enumeration e = p.keys();
          while (e.hasMoreElements()) {
            Object key = e.nextElement();
            System.out.println("  "+key + " = " + p.get(key));
          }
        } catch (SecurityException e) {
          System.out.println("not allowed to get Properties");
        }
      }

      // fetch previous configuration info
      if (!isApplet) {
        Rectangle b = (Rectangle) store.getBean("MainWindowBounds", null);
        if (b != null) {
          mainC.setBounds( b);
        } else
          mainC.setBounds( new Rectangle(50, 50, 810, 465)); // default  app size


        /* set Help directory; this is a kludge!!
        String helpDir = (String) store.get( "HelpDir");
        if (helpDir == null)
          helpDir = "/help/GDV"; */
        //ucar.unidata.ui.Help.setTopDir("/auxdata/javahelp/GDV");
      }

    // load protocol for ADDE URLs
    URLStreamHandlerFactory.install();
    URLStreamHandlerFactory.register("adde", new edu.wisc.ssec.mcidas.adde.AddeURLStreamHandler());

    // set Authentication for accessing passsword protected services like PUT
    java.net.Authenticator.setDefault(new thredds.ui.UrlAuthenticatorDialog(topLevel.getJFrame()));

      // here's the beef
    ui = new UI( topLevel, store);

      // add beans here
    ui.addMapBean( new thredds.viewer.gis.worldmap.WorldMapBean());
    ui.addMapBean( new thredds.viewer.gis.shapefile.ShapeFileBean("WorldDetailMap", "Global Detailed Map", "WorldDetailMap", "/resourcesOptional/maps/Countries.zip"));
    ui.addMapBean( new thredds.viewer.gis.shapefile.ShapeFileBean("USDetailMap", "US Detailed Map", "USMap", "/resourcesOptional/maps/US.zip"));
   }

    void saveConfig() {
      ui.storePersistentData();
      store.putBeanObject("MainWindowBounds", (Rectangle) mainC.getBounds());

      try {
        xstore.save();
      } catch (java.io.IOException ioe) {
        System.out.println("XMLStore failed "+ioe);
      }
    }

  } // end Common

}

/* Change History:
   $Log: Main.java,v $
   Revision 1.9  2004/10/15 19:16:08  caron
   enum now keyword in 1.5
   SelectDateRange send ISO date string

   Revision 1.8  2004/09/28 21:39:10  caron
   *** empty log message ***

   Revision 1.7  2004/05/21 05:57:35  caron
   release 2.0b

   Revision 1.6  2004/05/11 23:30:37  caron
   release 2.0a

   Revision 1.5  2004/02/21 02:18:50  caron
   add java.net.Authenticator.setDefault()

   Revision 1.4  2004/02/20 05:02:55  caron
   release 1.3

   Revision 1.3  2003/05/29 23:07:52  john
   bug fixes

   Revision 1.2  2003/01/07 14:57:19  john
   lib updates

   Revision 1.1  2002/12/13 00:51:11  caron
   pass 2

   Revision 1.3  2002/10/18 18:21:17  caron
   thredds server

   Revision 1.2  2002/04/29 22:39:22  caron
   add StationUI, clean up

   Revision 1.1.1.1  2002/02/26 17:24:48  caron
   import sources

*/
