package com.sun.solarisinstall.panels;

import com.sun.wizards.core.*;
import com.sun.wizards.nodes.*;
import com.sun.wizards.awt.*;
import com.sun.install.products.*;
import com.sun.install.panels.*;
import com.sun.solarisinstall.*;
import com.sun.solarisinstall.core.*;
import java.awt.*;
import java.util.*;

/**
 * The InitPanel is a node that kicks off a pfinstall dry run on
 * the server upon traversal and display of the tree.
 */
public class InitPanel extends WizardLeaf implements Runnable, ProgressMonitor
{
      Panel waitPanel = null;

      /*
       * how long this panel should take
       */
      public static final int PREINSTALL_TIME = 200;
      public static final int PFINSTALL_TIME = 150;

      private ProgressBar progress;
      private ProgressCounter timer;
      private Cursor defaultCursor;
      String selectedOS = null;
      boolean initialize = false;
      private static String loadString;
      
  /**
   * Creates an InitPanel with a route to the root of
   * the server object tree.
   */
  public InitPanel()
    {
    }

  /**
   * Creates an InitPanel with the specified name and WizardState.
   *
   * @param	wizardState	The buildtime WizardState.
   * @param	name		The name for this InitPanel.
   */
  public InitPanel(WizardState wizardState, String name)
    {
      super(wizardState, name);
    }
  
  /**
   * Creates an InitPanel with the specified name, the specified
   * route and wizard manager.
   *
   * @param name		The name for this InitPanel.
   * @param route		The route to the appropriate server side object.
   * @param wizardManager	The wizardManager responsible for this component.
   */
  public InitPanel(String name, Route route, WizardTreeManager wizardManager)
    {
      super(name, route, wizardManager);
    }

  public void createUI()
    {
      super.createUI();

      Boolean haveSolImage =
          (Boolean) wizardManager.callServerObjectMethod(
              getRoute().getChildServerRoute("profileObject"),
              "checkSolImage",
              null,null);
      if ( ! haveSolImage.booleanValue()) {
        selectedOS =
            (String)wizardManager.callServerObjectMethod(getRoute(),
            "getData",
            new String[]{"java.lang.String.class"},
            new Object[] { ProfileConstants.osName});

        if (selectedOS == null) selectedOS = "Solaris";
        Object[] arg =  {selectedOS};

        String msg = MsgCat.getString("com.sun.solarisinstall.SolarisInstall",
               SolarisInstallResources.MSG_NOT_FOUND, arg);
        String title = MsgCat.getString("com.sun.solarisinstall.SolarisInstall",
               SolarisInstallResources.MSG_ERROR);
        String ok =  MsgCat.getString("com.sun.solarisinstall.SolarisInstall",
               SolarisInstallResources.MSG_OK_DISK);

        displayQuery(this, title, msg,
             new String[] {ok},
             new String[] {null});

        getTreeManager().exit(1);
        return;
      }

     /*
      * Add the header (Please wait while the system is initializing...)
      */
      String heading = 
          MsgCat.getString("com.sun.solarisinstall.SolarisInstall", 
           SolarisInstallResources.MSG_HDR_INITIALIZING);
      add(new HeaderPanel(heading, null, 38), "North");

      loadString = 
         MsgCat.getString("com.sun.solarisinstall.SolarisInstall", 
                          SolarisInstallResources.MSG_PLEASE_WAIT);
      waitPanel = new Panel (new GridBagLayout());
      add(waitPanel, "Center");

      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridwidth = GridBagConstraints.REMAINDER;
      gbc.insets = new Insets(5,2,5,2);
      gbc.fill = GridBagConstraints.NONE;
      gbc.anchor = GridBagConstraints.SOUTH;
      waitPanel.add(new FlowLabel("<bold>" + loadString + "</bold>"), gbc);

      gbc.anchor = GridBagConstraints.NORTH;
      waitPanel.add(progress = new ProgressBar());
      /*
       * change cursor on entire frame
       */
      if (getTreeManager().hasGUI()) {
	 Component c = this;
	 while (c!=null && !(c instanceof Frame)) c=c.getParent();
	 if (c != null) {
	    defaultCursor = getCursor();
	    c.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
	 }
      }
      Thread t = new Thread(this);
      t.start();
    }
      
      public void consoleInteraction()
      {
	 String[] spinner = {"/", "-", "\\", "|"};
	 
	 TTYDisplay.showNewline();
	 String waiting = loadString+"  ";
	 TTYDisplay.print(waiting);
	 
	 int i=0;
	 while(!initialize) 
	 {
	    try
	    { 
	       TTYDisplay.print("\b"+spinner[i++ % spinner.length]);
	       Thread.sleep(800); 
	    }
	    catch(InterruptedException ie)
	    {
	    }
	 }
	 TTYDisplay.print("\b");
	 TTYDisplay.showNewline();
       TTYDisplay.showNewline();
     }

  public void run()
  {
    WizardTreeManager wizardManager = getTreeManager();

    timer = new ProgressCounter(this, PREINSTALL_TIME*1000, 0, 50);
    new Thread(timer).start();
    /*
     * Perform a sequence to run the preinstall script
     */
    wizardManager.callServerObjectMethod(
        getRoute(),
        "performSequence",
        new String[] {"com.sun.wizards.core.Route.class",
                      "java.lang.String.class",
                      "java.lang.Boolean.TYPE",
                      "java.lang.String.class"},
        new Object[] {getRoute(null),
                      "preinstallSequence",
                      new Boolean(false),
                      "finishInit"});

  }
  
   /*
    * Set the progress to the specified values.
    *
    * @param p	An array specifying progress.
    */
      public void setProgress(int p)
  {
     progress.setProgress(p);
  }
      
  public void finishInit()
  {
    WizardTreeManager wizardManager = getTreeManager();
    timer.complete();
    
    timer = new ProgressCounter(this, PFINSTALL_TIME*1000, 51, 100);
    new Thread(timer).start();
    selectedOS =
        (String)wizardManager.callServerObjectMethod(getRoute(),
        "getData",
        new String[]{"java.lang.String.class"},
        new Object[] { ProfileConstants.osName});

    /*
     * Save os directory in wizardState for patchpkg wizard
     */
    String osDir =
        (String) wizardManager.callServerObjectMethod(
            getRoute().getChildServerRoute("profileObject"),
            "calcOSDir",
            new String[]{"java.lang.String.class"},
            new Object[] { selectedOS});

    wizardManager.callServerObjectMethod(
        getRoute(),
        "setData",
        new String[] {"com.sun.wizards.core.Route.class",
                      "java.lang.String.class",
                      "java.lang.Object.class"},
        new Object[] {null, ProfileConstants.OSDirectory, osDir});


    /*
     * use os as label on panels.
     */
    wizardManager.callServerObjectMethod(
        getRoute(),
        "setData",
        new String[] {"com.sun.wizards.core.Route.class",
                      "java.lang.String.class",
                      "java.lang.Object.class"},
        new Object[] {null, ProfileConstants.progressName, selectedOS});

    /*
     * need to modify the progress label with the new product name
     */
    Object[] msgArgs = { selectedOS } ;
    Msg label = new Msg("com.sun.install.Install", 144, msgArgs);
    wizardManager.callServerObjectMethod(
        getRoute(),
        "setProgressLabel",
        new String[] {"java.lang.String.class",
                      "com.sun.wizards.core.Msg.class"},
        new Object[] {"install", label});

    /*
     * Set the frame title with selected OS
     */
    Msg title = new Msg("com.sun.solarisinstall.SolarisInstall",
                        SolarisInstallResources.MSG_INSTALLERNAME, msgArgs);
    wizardManager.callServerObjectMethod( getRoute(),
        "setData",
        new String[] {"com.sun.wizards.core.Route.class",
                      "java.lang.String.class",
                      "java.lang.Object.class"},
        new Object[] {null, InstallConstants.frameTitle, title});

    /*
     * initialize profile
     */
    wizardManager.callServerObjectMethod(
        getRoute().getChildServerRoute("profileObject"),
        "initProfile",
        null, null);

    // Check for swap location
    Boolean isSwapAtFront =
        (Boolean) wizardManager.callServerObjectMethod(
            getRoute().getChildServerRoute("profileObject"),
            "isSwapAtBeginning", null, null);

     wizardManager.callServerObjectMethod(
            getRoute(),
            "setData",
            new String[] {"com.sun.wizards.core.Route.class",
                          "java.lang.String.class",
                          "java.lang.Object.class"},
            new Object[] {null, "isSwapAtFront", isSwapAtFront});
     if (!isSwapAtFront.booleanValue()) {
       // Swap is not at beginning, no default install allowed
       wizardManager.callServerObjectMethod(
			getRoute(),
			"setData",
			new String[] {"com.sun.wizards.core.Route.class",
			               "java.lang.String.class",
					"java.lang.Object.class"}, 
			new Object[] {null, "",
					new Boolean(true)});
       wizardManager.callServerObjectMethod(
			getRoute(),
			"setData",
			new String[] {"com.sun.wizards.core.Route.class",
					"java.lang.String.class",
					"java.lang.Object.class"}, 
			new Object[] {null, InstallConstants.standardInstall,
				       new Boolean(false)});
     }
    /*
     * If there are no products due to dependency checking,
     * remove ProductSelectionPanel 
     */
    Vector allProductList =
        (Vector)wizardManager.callServerObjectMethod(
        getRoute().getChildServerRoute("profileObject"),
        "getProfileUtilProductList", null, null);

    Enumeration e = allProductList.elements();
    int prodnum = 0;
    while (e.hasMoreElements()) {
      SolarisProduct prod = (SolarisProduct)e.nextElement();
      if (prod.file.startsWith(ProfileConstants.pdFilePrefix)) {
        prodnum++;
        break;
      }
    }

    if (prodnum == 0) {
      wizardManager.callServerObjectMethod(
            getRoute(),
            "setData",
            new String[] {"com.sun.wizards.core.Route.class",
                          "java.lang.String.class",
                          "java.lang.Object.class"},
            new Object[] {null, ProfileConstants.noMedia, Boolean.TRUE});
    if (Def.DEBUG)System.out.println("\nInitPanel - no products, skip "+
                    "ProductSelectionPanel");
    }

    wizardManager.callServerObjectMethod(
        getRoute(),
        "setData",
        new String[] {"com.sun.wizards.core.Route.class",
                      "java.lang.String.class",
                      "java.lang.Object.class"},
        new Object[] {null, "initComplete", Boolean.TRUE});

    timer.complete();
    remove(waitPanel);
    // change cursor on entire frame
    if (getTreeManager().hasGUI()) {
       Component c = this;
       while (c!=null && !(c instanceof Frame)) c=c.getParent();
       if (c != null && defaultCursor != null) 
	  c.setCursor(defaultCursor);
    }
      
    initialize = true;
    if (wizardManager.hasGUI())
    {
       wizardManager.nextButtonPressed();
    }
  }


  public int getButtonMask()
  {
    if (!initialize)
       return(0);
    return (super.getButtonMask());

  }


  /**
   * Get the runtime classes required by this panel.
   */
  public void addRuntimeResources(Vector resourceVector)
  {
    super.addRuntimeResources(resourceVector);
    resourceVector.addElement(new String[] {null,
			      "com.sun.solarisinstall.panels.InitPanel"});
    resourceVector.addElement(new String[] {null,
			      "com.sun.solarisinstall.core.ProgressMonitor"});
    resourceVector.addElement(new String[] {null,
			      "com.sun.solarisinstall.core.ProgressCounter"});
    resourceVector.addElement(new String[] {null,
			      "com.sun.wizards.awt.ProgressBar"});
    
    resourceVector.addElement(new String[] {null,
			"com.sun.solarisinstall.panels.VTOC"});
    resourceVector.addElement(new String[] {null,
			"com.sun.solarisinstall.panels.VTOCEntry"});
    resourceVector.addElement(new String[] {null,
			"com.sun.solarisinstall.panels.ExtendedDiskInfo"});

  }
}


