/*
Copyright 1990-2001 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/


package sun.awt.im.iiimp;

import java.util.*;
import java.util.jar.*;
import java.net.*;
import java.io.*;

import com.sun.iiim.*;

public class AuxProxy extends Thread implements IIIMProtocol {

    public static void main(String[] args) {
	SecurityManager sm = new SecurityManager();
	System.setSecurityManager(sm);
	AuxProxy t = new AuxProxy();
	t.start();
    }

    private IIIMPInputStream in;
    private IIIMPOutputStream out;
    private String hostName;
    private int imID;
    private int icID;
    private HashSet doSet;
    private HashMap auxMap;
    private static ODClassLoader odLoader;
    private IIIMPURLConnection uc;

    public void run() {
	// connection setup
	try {
	    hostName = InetAddress.getLocalHost().getHostName();

	    Manager.initProps();
	    String urlString = Manager.getProperty("iiimp.server");
	    if (urlString == null) {
		urlString = "iiimp://" + hostName + ":9010";
	    }
	    URL url = new URL(urlString);
	    uc = (IIIMPURLConnection)url.openConnection();

	    if (!uc.isConnected()) {
		uc.connect();

		if (!uc.isConnected()) {
		    throw new IOException();
		}
	    }
	    in = new IIIMPInputStream(uc.getInputStream());
	    out = new IIIMPOutputStream(uc.getOutputStream());
	    doSet = new HashSet();
	    auxMap = new HashMap();
	    odLoader = new ODClassLoader();

	    imConnect();
	    
	    while(true) {
		Protocol protocol = new Protocol();
		protocol.read(in);
		try {
		    driveProtocol(protocol);
		} catch(Exception e) {
		    if (Manager.DEBUG) {
			e.printStackTrace();
		    }
		    System.exit(1);
		}
	    }

	} catch(Exception e) {
	    if (Manager.DEBUG) {
		e.printStackTrace();
	    }
	    System.exit(1);
	}
    }

    static final String CLIENT_TYPE = "JavaAuxProxy";

    static public ODClassLoader getLoader() {
	return odLoader;
    }

    private void imConnect() throws IOException {
	String userName = System.getProperty("user.name", null);
	userName += "@" + hostName;
	ProtocolData data = new ProtocolData();
	data.write(BIGENDIAN);
	data.write(VERSION);
	data.writeString(userName);
	data.write2(0);
	send(new Protocol(IM_CONNECT, data));
	getReply(IM_CONNECT_REPLY);
    }

    /**
     * This will receive object donwloading candidate
     * before get IM_SETVALUES_REPLY
     */
    void setClientType() {
	try {
	    ProtocolData data = new ProtocolData();
	    data.write2(imID);
	    data.write2(0); // pad

	    IIIMPClientDescripter desc = new IIIMPClientDescripter();
	    ProtocolData d = desc.getData();
	    data.write4(d.count);
	    data.writeBytes(d.buf, d.count);

	    send(new Protocol(IM_SETIMVALUES, data));
	    getReply(IM_SETIMVALUES_REPLY);
	} catch(Exception e) {
	    if (Manager.DEBUG) {
		e.printStackTrace();
	    }
	}
    }

    void downloadObject() {
	if (doSet.size() == 0) {
	    return;
	}
	try {
	    ProtocolData data = new ProtocolData();
	    data.write2(imID);
	    data.write2(0); // pad
	    data.write4(doSet.size() * 2);

	    Iterator it = doSet.iterator();
	    while(it.hasNext()) { 
		IIIMPObjectDescripter desc =
		    (IIIMPObjectDescripter)it.next();
		data.write2(desc.getDAttribID());
		debug(desc.toString());
	    }
		
	    data.pad();
	    send(new Protocol(IM_GETIMVALUES, data));
	    getReply(IM_GETIMVALUES_REPLY);
	} catch(Exception e) {
	    if (Manager.DEBUG) {
		e.printStackTrace();
	    }
	}
    }

    public void dispatchAuxEvent(IIIMAuxEvent e) {
	int[] idata;
	String[] sdata; 
	try {
	    ProtocolData data = new ProtocolData();

	    data.write2(imID);
	    data.write2(icID);
	    data.write4(e.getIndex());
	    data.writeString(e.getName());
	    if ((idata = e.getIntValues()) == null) {
		data.write4(0);
	    } else {
		data.write4(idata.length * 4);
		for (int i = 0; i < idata.length; i++) {
		    data.write4(idata[i]);
		}
	    }
	    if ((sdata = e.getStringValues())== null) {
		data.write4(0);
	    } else {
		ProtocolData d = new ProtocolData();
		for (int i = 0; i < sdata.length; i++) {
		    d.writeString(sdata[i]);
		}
		data.write4(d.count);
		data.writeBytes(d.buf, d.count);
	    }
	    send(new Protocol(IM_AUX_SETVALUES, data));
	} catch(Exception ex) {
	    if (Manager.DEBUG) {
		ex.printStackTrace();
	    }
	}
    }

    void createPseudoIC() {
	try {
	    send(new Protocol(IM_CREATEIC, ProtocolDriver.getCreateICData(imID)));
	    getReply(IM_CREATEIC_REPLY);
	} catch(Exception e) {
	    if (Manager.DEBUG) {
		e.printStackTrace();
	    }
	}
    }

    void getReply(int protocolID) throws IOException {
	try {
	    Protocol protocol = new Protocol();
	    protocol.read(in);
	    driveProtocol(protocol);
	} catch(Exception e) {
	    if (Manager.DEBUG) {
		e.printStackTrace();
	    }
	}
    }
    
    private void driveProtocol(Protocol protocol) throws IOException {
	int opcode = protocol.getOpCode();
	ProtocolData data = protocol.getData();
	ProtocolData replyData = new ProtocolData();

	imID = data.read2();
	switch(opcode) {
	  case IM_SETIMVALUES:
	    data.read2(); // pad
	    int length = data.read4();

	    if (length > 0) {
		while(data.available() > 0) {
		    int type = data.read2();
		    data.read2(); // pad
		    int size = data.read4();
		    byte[] buf = new byte[size];
		    data.read(buf, 0, size);
		    ProtocolData adata = new ProtocolData(buf);
		    switch(type) {
		      case INPUTMETHOD_LIST:
			debug(" im list");
			break;
		      case OBJECT_DESCRIPTER_LIST:
			debug(" obj desc list");
			while(adata.available() > 0) {
			    int objCategory = adata.read2();
			    adata.read2(); // pad
			    int objSize = adata.read4();
			    int attribID = adata.read2();
			    int dattribID = adata.read2();
			    String objName = adata.readString();
			    String objHRN = adata.readString();
			    String objSignature = adata.readString();
			    String objUser = adata.readString();
			    IIIMPObjectDescripter objDesc =
				new IIIMPObjectDescripter(objCategory,
							  objSize,
							  attribID,
							  dattribID,
							  objName,
							  objHRN,
							  objSignature,
							  objUser);
			    doSet.add(objDesc);
			}
			break;
		      case CCDEF:
			debug(" ccdef");
			break;
		      case GUI_OBJECT:
			debug(" gui obj");
			break;
		      case LWE_OBJECT:
			debug(" lwe obj");
			break;
		      default:
			debug(" unknown");
			break;
		    }
		}
	    }
	    replyData.write2(imID);
	    replyData.write2(0); // pad
	    send(new Protocol(IM_SETIMVALUES_REPLY, replyData));
	    break;
	  case IM_SETIMVALUES_REPLY:
	    break;
	  case IM_GETIMVALUES_REPLY:
	    data.read2(); // pad
	    data.read4(); // size, not used

	    while(data.available() > 7) {
		debug(" available = " + data.available());
		int attrID = data.read2();
		debug(" attrID = " + attrID);
		data.read2(); // pad
		int size = data.read4();
		debug(" attrsize = " + size);
		if (size > 0) {
		    int classNameListSize = data.read4();
		    debug(" cnls = " + classNameListSize);
		    ProtocolData classNameData =
			new ProtocolData(data.buf, data.pos, classNameListSize);
		    data.skipBytes(classNameListSize);
		    while(classNameData.available() > 0) {
			String className = classNameData.readString();
			debug(" class = " + className);
		    }
		    int jarSize = data.read4();
		    debug(" jar size = " + jarSize);
		    byte[] attrval = new byte[jarSize];
		    data.read(attrval, 0, jarSize);

		    JarInputStream jis =
			new JarInputStream(new ByteArrayInputStream(attrval));
		    
		    odLoader.addJar(jis);
		    
		    int pad = ProtocolData.paddings(size);
		    debug(" paddings = " + pad);
		    for (int i = 0; i < pad; i++) {
			data.read();
		    }
		}
	    }
	    break;
	  case IM_REGISTER_TRIGGER_KEYS:
	    break;
	  case IM_CONNECT_REPLY:
	    int langLen = data.read2();
	    debug(" langLen = " + langLen);
	    while(data.available() > 0) {
		debug(" lang = " + data.readString());
	    }
	    setClientType();
	    downloadObject();
	    createPseudoIC();
	    break;
	  case IM_CREATEIC_REPLY:
	    icID = data.read2();
	    debug(" CREATEIC_REPLY icID = " + icID);
	    ProtocolData d = new ProtocolData();
	    d.write2(imID);
	    d.write2(icID);
	    send(new Protocol(IM_SETICFOCUS, d));
	    getReply(IM_SETICFOCUS_REPLY);
	    break;
	  case IM_AUX_START: {
	      icID = data.read2();
	      
	      int index = data.read4();
	      String name = data.readString();
	      debug(" AUX START by PROXY - " + name);
	      
	      try {
		  IIIMAuxListener aux =
		      (IIIMAuxListener)odLoader.loadClass(name).newInstance();
		  auxMap.put(name, aux);
		  ((IIIMComponent)aux).setProxy(this);
		  aux.auxStart(new IIIMAuxEvent(IIIMAuxEvent.START,
						index, name));
	      } catch(Exception e) {
		  if (Manager.DEBUG) {
		      e.printStackTrace();
		  }
	      }

	      replyData.write2(imID);
	      replyData.write2(icID);
	      replyData.write4(index);
	      replyData.writeString(name);
	      send(new Protocol(IM_AUX_START_REPLY, replyData));
	      break;
	  }
	  case IM_AUX_DRAW: {
	      icID = data.read2(); // ic
	      int index = data.read4(); // aux index
	      String name = data.readString();
	      int intSize = data.read4();
	      int[] intA = new int[intSize / 4];
	      for (int i = 0; i < intA.length; i++) {
		  intA[i] = data.read4();
	      }
	      int strSize = data.read4();
	      Vector v = new Vector();
	      while(data.available() > 0) {
		  v.add(data.readString());
	      }
	      String[] strA = new String[v.size()];
	      for (int i = 0; i < v.size(); i++) {
		  strA[i] = (String)v.elementAt(i);
	      }
	      
	      IIIMAuxListener aux = (IIIMAuxListener)auxMap.get(name); 
	      if (aux == null) {
		  debug(" Unknown aux : " + name);
		  break;
	      }
	      
	      debug(" aux draw.");

	      aux.auxDraw(new IIIMAuxEvent(IIIMAuxEvent.DRAW,
					   index, name, intA, strA));
	      replyData.write2(imID);
	      replyData.write2(icID);
	      replyData.write4(index);
	      replyData.writeString(name);
	      send(new Protocol(IM_AUX_DRAW_REPLY, replyData));
	      break;
	  }
	  case IM_AUX_DONE:
	    icID = data.read2();
	    int index = data.read4();
	    String name = data.readString();
	    IIIMAuxListener aux = (IIIMAuxListener)auxMap.get(name);
	    if (aux == null) {
		debug(" Unknown aux : " + name);
		break;
	    }
	    aux.auxDone(new IIIMAuxEvent(IIIMAuxEvent.DONE, index, name));
	    replyData.write2(imID);
	    replyData.write2(icID);
	    replyData.write4(index);
	    replyData.writeString(name);
	    send(new Protocol(IM_AUX_DONE_REPLY, replyData));
	    break;
	  case IM_AUX_SETVALUES_REPLY:
	    break;
	  case IM_SETICFOCUS_REPLY:
	    break;
	  default:
	    debug("AuxProxy does not intend to receive " + protocol);
	}
    }

    private synchronized void send(Protocol protocol) throws IOException {
	protocol.write(out);
	out.flush();
    }

    private void debug(String str) {
	if (Manager.DEBUG) {
	    System.err.println(str);
	}
    }

    private static final String IIIMP_PKG_PREFIX = "sun.awt.im";
    private static final String JAVA_PROTOCOL_HANDLER_PKGS =
	"java.protocol.handler.pkgs";

    static {
	// Add sun.awt.im to the java.protocol.handler.pkgs property
	// if it is not defined yet.
	Properties defaults = System.getProperties();
	synchronized(defaults) {
	    String pkgs = defaults.getProperty(JAVA_PROTOCOL_HANDLER_PKGS);
	    if (pkgs == null) {
		pkgs = IIIMP_PKG_PREFIX;
	    } else {
		StringTokenizer st = new StringTokenizer(pkgs, "|");
		boolean hasIIIMP = false;
		while(st.hasMoreTokens()) {
		    if (st.nextToken().equals(IIIMP_PKG_PREFIX)) {
			hasIIIMP = true;
		    }
		}
		if (!hasIIIMP) {
		    pkgs += "|" + IIIMP_PKG_PREFIX;
		}
	    }
	    defaults.put(JAVA_PROTOCOL_HANDLER_PKGS, pkgs);
	}
    }
}
