/*
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2006 Phex Development Group
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 *  --- CVS Information ---
 *  $Id: Main.java 3362 2006-03-30 22:27:26Z gregork $
 */
package phex;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import org.apache.commons.lang.SystemUtils;

import phex.common.Environment;
import phex.common.ManagerController;
import phex.common.ThreadTracking;
import phex.connection.LoopbackDispatcher;
import phex.connection.NetworkManager;
import phex.gui.common.*;
import phex.utils.*;


public class Main
{
    /**
     * Dont use NLogger before arguemnts have been read ( -c )
     * @param args
     */
    public static void main( String args[] )
    {
        long start = System.currentTimeMillis();
        long end;
        
        validateJavaVersion();

        // parse args...
        Iterator iterator = Arrays.asList( args ).iterator();
        
        String startupUri = null; 
        String loopbackUri = null;
        String magmaFile = null;
        String rssFile = null; 
        String argument;
        // Optionally add an Uri to show for download at startup
        // startupUri = "magnet"; 
        while ( (argument = readArgument( iterator ) ) != null ) 
        {
            if ( argument.equalsIgnoreCase("-c") )
            {
                String path = readArgument(iterator);
                if (path != null)
                {
                    File configRoot = new File(path);
                    try
                    {
                        Environment.getInstance().setPhexConfigRoot(configRoot);
                    } catch (IOException exp)
                    {
                        exp.printStackTrace();
                    }
                }
            }
            else if ( argument.equalsIgnoreCase("-uri") )
            {
                loopbackUri = readArgument(iterator);
            }
            else if ( argument.equalsIgnoreCase("-magma") )
            {
                magmaFile = readArgument(iterator);
            }
            else if ( argument.equalsIgnoreCase("-rss") )
            {
                rssFile = readArgument(iterator);
            }
        }
        
        if ( loopbackUri != null && LoopbackDispatcher.dispatchUri( loopbackUri ) )
        {// correctly dispatched uri
            System.exit( 0 );
        }
        if ( magmaFile != null && LoopbackDispatcher.dispatchMagmaFile( magmaFile ) )
        {// correctly dispatched uri
            System.exit( 0 );
        }
        if ( rssFile != null && LoopbackDispatcher.dispatchRSSFile( rssFile ) )
        {// correctly dispatched uri
            System.exit( 0 );
        }
        
        try
        {
            SplashWindow splashWindow = null;
            try {
                splashWindow = new SplashWindow();
                splashWindow.showSplash();
            }
            catch ( java.awt.HeadlessException ex )
            {
                // running in headless mode so of course the splash
                // doesn't work
            }
            Localizer.initialize();
            ThreadTracking.initialize();
            ManagerController.initializeManagers();

            end = System.currentTimeMillis();
            Logger.logMessage( Logger.FINEST, Logger.GLOBAL,
                "Pre GUI startup time: " + (end-start) );

            try 
            {
                GUIRegistry.getInstance().initialize();
            }
            catch ( ExceptionInInitializerError ex )
            {
                // running in headless mode so of course this
                // doesn't work
            }
            if ( splashWindow != null ) splashWindow.dispose();
            MainFrame mainFrame = null;
            mainFrame = GUIRegistry.getInstance().getMainFrame();
            if ( mainFrame != null )
                mainFrame.setVisible(true);
            
            end = System.currentTimeMillis();
            Logger.logMessage( Logger.FINEST, Logger.GLOBAL,
                "Full startup time: " + (end-start) );
                
            ManagerController.startupCompletedNotify();
            
            if ( startupUri != null )
            {// Startup-Uri included. 
            	NetworkManager.getInstance().fireIncomingUriDownload(startupUri); 
            }
            if ( loopbackUri != null )
            {// correctly dispatched uri
                NetworkManager.getInstance().fireIncomingUriDownload(loopbackUri);
            }
            if ( magmaFile != null )
            {// correctly dispatched uri
                NetworkManager.getInstance().fireIncomingMagmaDownload(magmaFile);
            }
            if ( rssFile != null )
            {// correctly dispatched uri
                NetworkManager.getInstance().fireIncomingRSSDownload(magmaFile);
            }
        }
        catch ( Throwable th )
        {
            th.printStackTrace();
            NLogger.error( NLoggerNames.GLOBAL, th, th );
            // unhandled application exception... exit
            System.exit( 1 );
        }
    }

    /**
     * @param iterator
     * @return
     */
    private static String readArgument(Iterator iterator)
    {
        if ( !iterator.hasNext() )
        {
            return null;
        }
        String value = (String) iterator.next();
//        if ( value.startsWith( "\"" ))
//        {
//            while (iterator.hasNext())
//            {
//                String additional = (String)iterator.next();
//                value += additional;
//                if ( additional.endsWith("\""))
//                {
//                    break;
//                }
//            }
//            if ( !value.endsWith("\"") )
//            {
//                throw new IllegalArgumentException( "Unterminated argument" );
//            }
//            // cut of starting and ending "
//            value = value.substring( 1, value.length() - 1 );
//        }
        return value;
    }

    /**
     * 
     */
    private static void validateJavaVersion()
    {
        if ( SystemUtils.isJavaVersionAtLeast( 1.4f ) )
        {
            return;
        }
        
        JFrame frame = new JFrame( "Wrong Java Version" );
        frame.setSize( new Dimension( 0, 0 ) );
        frame.setVisible(true);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension winSize = frame.getSize();
        Rectangle rect = new Rectangle(
            (screenSize.width - winSize.width) / 2,
            (screenSize.height - winSize.height) / 2,
            winSize.width, winSize.height );
        frame.setBounds(rect);
        JOptionPane.showMessageDialog( frame,
            "Please use a newer Java VM.\n" +
            "Phex requires at least Java 1.4.0. You are using Java " + SystemUtils.JAVA_VERSION + "\n" +
        	"To get the latest Java release go to http://java.com.",
            "Wrong Java Version", JOptionPane.WARNING_MESSAGE );
        System.exit( 1 );
    }
}
