/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.tools.upgrade.common;


import java.util.logging.*;
import java.lang.reflect.Constructor;
import java.util.Enumeration;
import java.util.Vector;
import java.util.HashMap;
import java.util.StringTokenizer;

import com.sun.enterprise.tools.upgrade.common.arguments.ParsedArgument;
import com.sun.enterprise.tools.upgrade.common.arguments.ARG_help;
import com.sun.enterprise.tools.upgrade.common.CommonInfoModel;
import com.sun.enterprise.tools.upgrade.logging.*;
import com.sun.enterprise.util.i18n.StringManager;

/**
 * Parse the arguments for the upgrade tool
 * and invoke the appropriate handler
 *
 * @author Hans Hrasna
 */
public class ArgsParser {
    
    public static final String SOURCE = "source";
    public static final String SOURCE_SHORT = "s";
    public static final String TARGET = "target";
    public static final String TARGET_SHORT = "t";
    public static final String DOMAIN = "domain";
    public static final String DOMAIN_SHORT = "d";
    public static final String NSSPWD = "nsspwd";
    public static final String NSSPWDFILE = "nsspwdfile";
    public static final String NSSPWDFILE_SHORT = "n";
    public static final String TARGETNSSPWD = "targetnsspwd";
    public static final String TARGETNSSPWDFILE = "targetnsspwdfile";
    public static final String TARGETNSSPWDFILE_SHORT = "e";
    public static final String JKSPWD = "jkspwd";
    public static final String JKSPWDFILE = "jkspwdfile";
    public static final String JKSPWDFILE_SHORT = "j";
    public static final String CAPWD = "capwd";
    public static final String CAPWDFILE = "capwdfile";
    public static final String CAPWDFILE_SHORT = "p";
    public static final String ADMINUSER = "adminuser";
    public static final String ADMINUSER_SHORT = "a";
    public static final String ADMINPASSWORD = "adminpassword";
    public static final String ADMINPASSWORD_SHORT = "w";
    public static final String MASTERPASSWORD = "masterpassword";
    public static final String MASTERPASSWORD_SHORT = "m";
    public static final String CLINSTANCEINFO = "clinstancefiles";
    public static final String CLINSTANCEINFO_SHORT = "i";
    
    private static Logger _logger=LogService.getLogger(LogService.UPGRADE_LOGGER);
    private String [] arguments;
    private CommonInfoModel commonInfo;
    private HashMap interactiveMap;
    private StringManager sm;
    
    /** Creates a new instance of ArgsParser */
    public ArgsParser(String [] args, CommonInfoModel infoModel, HashMap hMap) {
        sm = StringManager.getManager(LogService.UPGRADE_CLI_LOGGER);
        commonInfo = infoModel;
        interactiveMap = hMap;
        arguments = args;
    }
    
    public ArgsParser(String [] args, CommonInfoModel infoModel) {
        this(args, infoModel, new HashMap());
    }
    
    public HashMap parse() {
        return parse(null);
    }
    
    public HashMap parse(InteractiveInput interactiveParser) {
        String cmd = null;
        Vector parameters = new Vector();
        Vector instructions = new Vector();
        Class instructionHandler = null;
        
        for(int i=0;i<arguments.length;i++) {
            if(arguments[i].startsWith("-")){
                String rawArg = arguments[i];
                String argument = rawArg.substring(rawArg.lastIndexOf("-") + 1, rawArg.length()); //strip - or --
                String delimeters = "=";
                StringTokenizer st = new StringTokenizer(argument, delimeters, false);
                if ( st.hasMoreTokens() ) {
                    cmd = st.nextToken();
                    if(cmd.equals("?")) cmd = "h";
                    instructionHandler = getHandler(cmd);
                    parameters = new Vector();
                }
                if (st.hasMoreTokens()) { //there was an equal sign
                    parameters.add(st.nextToken());
                }
                while(i + 1 < arguments.length && !arguments[i + 1].startsWith("-")) {
                    i++;
                    parameters.add(arguments[i]);
                }
                if ( instructionHandler != null ) {
                    interactiveMap.put(cmd, parameters);
                    instructions.addElement(new ParsedArgument(instructionHandler, cmd, parameters, commonInfo, interactiveMap));
                } else {
                    String msg = sm.getString("enterprise.tools.upgrade.cli.invalid_option",rawArg);
		    //start CR 6396918
		    if(cmd.equals(ADMINPASSWORD_SHORT) || cmd.equals(ADMINPASSWORD)) {
			msg = msg + "\n" + sm.getString("enterprise.tools.upgrade.cli.deprecated_option",rawArg) + 
			    " " + sm.getString("enterprise.tools.upgrade.cli.deprecated_option.adminpassword");
		    }
		    //end CR 6396918
                    helpUsage(msg);
                    System.exit(1);
                }
            }
        }
        
        //now process the parsed instructions
        Enumeration e = instructions.elements();
        while ( e.hasMoreElements() ) {
            ParsedArgument  pi = (ParsedArgument )e.nextElement();
            instructionHandler = pi.getHandler();
            try {
                Class [] parameterTypes = new Class [] {pi.getClass()};
                Constructor constructor = instructionHandler.getConstructor(parameterTypes);
                constructor.newInstance(new Object [] { pi });
            } catch (Exception ex) {
                _logger.log(Level.INFO, sm.getString("enterprise.tools.upgrade.cli.invalid_option", pi.getMneumonic()), ex);
                System.exit(1);
            }
            
        }

        if(interactiveParser != null) {
            interactiveParser.collectMissingArguments(interactiveMap);
        }
        
        return interactiveMap;
    }
    
    private Class getHandler(String cmd) {
        Class instructionHandler = null;
        try {
	    //start CR 6396918
	    if(cmd.equals(ADMINPASSWORD_SHORT) || cmd.equals(ADMINPASSWORD)) 
                instructionHandler = null;
	    else 
	    //end CR 6396918
		instructionHandler = Class.forName("com.sun.enterprise.tools.upgrade.common.arguments.ARG_" + cmd );
            return instructionHandler;
        } catch (ClassNotFoundException cnf) {
            
        } catch (Exception e1) {
            _logger.log(Level.INFO, sm.getString("enterprise.tools.upgrade.cli.invalid_option",e1), e1);
        }
        return null;
    }
    
    public void helpUsage(String str){
        System.out.println("\n" + str + "\n");
        helpUsage();
    }
    
    public void helpUsage(){
        commonInfo.recover();
        new ARG_help(new ParsedArgument(null, null, null, commonInfo, null));
    }
}
