/*
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2004 Gregor Koukkoullis ( phex <at> kouk <dot> de )
 *
 *  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,v 1.14 2004/09/26 01:27:10 nxf Exp $
 */
package phex;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.io.*;
import java.util.*;

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

import org.apache.commons.lang.SystemUtils;


import phex.common.*;
import phex.gui.common.*;
import phex.utils.*;


public class Main
{
    public static void main( String args[] )
    {
        long start = System.currentTimeMillis();
        long end;
        
        validateJavaVersion();

        // parse args...
        Iterator iterator = Arrays.asList( args ).iterator();
        String argument = readArgument( iterator );
        
        if ( argument != null && 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();
                }
            }
        }


        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();
            Environment.getInstance().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.show();
            
            end = System.currentTimeMillis();
            Logger.logMessage( Logger.FINEST, Logger.GLOBAL,
                "Full startup time: " + (end-start) );
                
            Environment.getInstance().startupCompletedNotify();
        }
        catch ( Throwable th )
        {
            th.printStackTrace();
            Logger.logError( 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.show();
        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 );
    }
}
