/*$cb
 *    This file is a part of libopenmhp.
 *
 *    Copyright (C) 2005 Mikko Novaro <miknov@gmail.com>
 *
 *    See main header file (libopenmhp/openmhp.h) for licensing and
 *    contact information.
 $ce*/

package libopenmhp;

import java.io.*;

import libopenmhp.message.*;
import libopenmhp.xmlhandler.XMLHandler;
import org.openmhp.system.AppsDatabaseServer;

// EventManager + others:
import org.dvb.event.*;

public class InterfaceServer {

    public static final String CLIENTTOMHP_FIFO = "/tmp/libopenmhp-clienttomhp";
    public static final String MHPTOCLIENT_FIFO = "/tmp/libopenmhp-mhptoclient";

    private static InterfaceServer activeInstance;

    public static EventManager eventManager;

    private DataOutputStream mhpToClient; // PrintStream mhpToClient;
    private InputStream clientToMhp;

    private boolean mhpToClientConnected;
    private StringBuffer mhpToClientBuffer;

    /** TODO: pass fifo paths as arguments. */
    private InterfaceServer() throws Exception {
	assert activeInstance == null;
	activeInstance = this;
	mhpToClientConnected = false;
	mhpToClientBuffer = new StringBuffer();
	/* Opening fifos must be done in the same order than on CLIENT's
	 * side. */
	clientToMhp = new FileInputStream(new File(CLIENTTOMHP_FIFO));
	// mhpToClient = new PrintStream(new FileOutputStream(new File(MHPTOCLIENT_FIFO)));
	mhpToClient = new DataOutputStream(new FileOutputStream(new File(MHPTOCLIENT_FIFO)));
	mhpToClientConnected = true;
	Debug.dbg(this, "beginning XML communication mhp->client");
	sendMessage("<mhptoclient>");
	sendMessage(mhpToClientBuffer.toString());
    }

    public static InterfaceServer getInstance() {
	if (activeInstance == null) try {
	    activeInstance = new InterfaceServer();
	} catch (Exception e) {}
	return activeInstance;
    }

    public synchronized void sendMessage(Message msg) {
	sendMessage(msg.toString());
    }

    /** Sends a message to client. The entire base+1 depth XML message
     * should be sent with a single invocation. */
    private synchronized void sendMessage(String msg) {
	Debug.dbg(this, "sending xml message \""+ msg + "\"");
	if (mhpToClientConnected) {
	    try {
		mhpToClient.writeBytes((msg+"\n"));
		mhpToClient.flush();
	    } catch (IOException ex) {
		Debug.err(this, "writing message failed.");
	    }
	}
	else {
	    mhpToClientBuffer.append(msg);
	}
    }

    public void endConnection() {
	sendMessage("</mhptoclient>");
    }

    public void startServer() throws Exception {
        eventManager = EventManager.getInstance();
        XMLHandler hand = null;
	hand = new XMLHandler(clientToMhp);
	hand.runHandler();
	clientToMhp.close();
    }

}
