package org.jcon.ba.lib;

import org.jcon.ba.system.BeanActionStart;
import org.jcon.util.msg.MessageDef;
import org.jcon.util.msg.Message;
import org.jcon.util.msg.MessageService;
import org.jcon.util.msg.MessageSourceStd;
import org.jcon.util.service.ContainerServices;
import org.jcon.util.service.ContainerServicesUser;
import org.jcon.util.GenLib;
import org.jcon.io.TextResource;

import java.net.URL;
import java.util.Vector;

public class HelpSystem extends MessageSourceStd
  implements MessageService, ContainerServicesUser, BeanActionStart {

  private ContainerServices containerServices;
  private Object marker;


  public void setMarkerClass(Object o) {
    marker = o;
  }

  public void start() {
    p("helpsytem starting");
      Message message = new Message("AcquireSystemProperty");
      message.setString("PropertyName","HelpMarkerClassName");
      containerServices.sendMessage(message);
      String value = message.getString("PropertyValue");
      p("value = " + value);
      Object markerclass = GenLib.createInstance(value);
      setMarkerClass(markerclass);
  }

  public void serviceMessage(Message message) {
    Object helpfile;
    //    p("Help System got the message: " + message);


    if(message.getName() == "HelpRequested") {
      Message msg = new Message("StartHelpViewer");
      getMessageRouter().fire(msg);
      //    p("sent the message " + msg);
      msg = new Message("ShowHelp");
      String helpid = (String)message.get("HelpId");
      if(marker == null) {
	p("ERROR the marker class is null!");
      }
      TextResource tr = new TextResource(marker,helpid);
      helpfile = tr.readString();
      //    p("contents = " + helpfile);
      msg.set("content",helpfile);
      // p("the helpid = " + helpid);
      //    ClassLoader cl = HelpSystem.class.getClassLoader();
      getMessageRouter().fire(msg);
      //    p("sent the message " + msg);
      return;
    }

  }

  public Vector getMessageDefs() {
    return null;
  }

  public MessageDef[] getServiceMessageDefs() {
    MessageDef[] defs = new MessageDef[1];
    defs[0] = new MessageDef("HelpRequested", this);
    defs[0].add("HelpId", String[].class, "help id string");
    return defs;
  }



  //---------- ContainerServicesUser Implementation --------
  public void setContainerServices(ContainerServices services) {
    containerServices = services;
  }
  public String[] getContainerServicesInterests() {
    return new String[] {"HelpViewer"}; 
  }



  private static void p(String s) {
    System.out.println(s);
  }

}
