/********************************************************************
 * Copyright © 2004 EDS. All rights reserved
 ********************************************************************/
package gov.vha.edb.rules.builder;

import ilog.rules.repository.model.IlrRepository;
import gov.vha.edb.rules.repository.EDBRepository;

import java.util.ArrayList;

//framework
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <p>Launch the Rule Builder with a specific mode according to the login value.</p>
 */
public class EDBBuilder 
{
	private static Log logger = LogFactory.getLog(EDBBuilder.class);
	
	public static void main(String[] args) {
		IlrRepository repository = ilog.rules.tools.IlrBuilder.getRepository();
		if (!(repository instanceof EDBRepository)) {
			log("Repository must be an instance of " + EDBRepository.class.getName());
			log("The builder will exit");
			quit(-1);
		}    
		
		
	    EDBLoginDialog login = new EDBLoginDialog();
	    login.show();
	    login.toFront();
		
	    EDBRepository rep = (EDBRepository)repository;
	    rep.selectCurrentRole(login.getUserName(), login.getPassword());
	    String currentUser = rep.getCurrentUser();
	    if (currentUser != null) {
	    	// Log builder login name instead of system login name
	    	// for history events.
	    	if (rep.getHistoryManager() != null) {
	    		rep.getHistoryManager().getCurrentSession().setInfo(currentUser);
	    	}
	    }
	
	    String mode = rep.getCurrentRole();
		// launch the builder with correct mode
	    ilog.rules.tools.IlrBuilder.main(buildArgumentLine(args, mode));
  }

  protected static void quit(int code) {
    System.exit(code);
  }

  private static String[] buildArgumentLine(String[] args, String mode) {
    int c = 0;
    int len = args.length;
    boolean hasMode = false;
    ArrayList argList = new ArrayList();
    while (c < len) {
      String arg = args[c++];
      if (arg.equals("-mode")) {//I18N
        if (c >= len) {
          log("Wrong argument for the command " + arg.substring(1));
          log("The builder will exit");
          quit(-1);
        }
        argList.add(arg);
        argList.add(mode);
        hasMode = true;
        c++;
      } 
      else{
        argList.add(arg);
      }
    }
    if (!hasMode) {
      argList.add("-mode");
      argList.add(mode);
    }
    
    return (String[])argList.toArray(new String[argList.size()]);
  }
  
  /**
   * A helper method to log debug information.
   * @param info the information to log.
   */
  private static void log(String info){
  	if (logger.isDebugEnabled()) {
  		logger.info(info);
  	}
  }
}
