/**
 * 
 * Copyright 2005 Protique Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.activemq.transport.jabber;

import EDU.oswego.cs.dl.util.concurrent.Executor;
import org.activemq.message.Packet;
import org.activemq.transport.tcp.TcpTransportChannel;
import org.activemq.transport.tcp.TcpTransportServerChannel;
import org.activemq.transport.tcp.TcpBufferedOutputStream;
import org.activemq.transport.TransportStatusEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.jms.JMSException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.net.Socket;
import java.net.URI;
import java.io.*;

/**
 * A transport for using Jabber (XMPP) to talk to ActiveMQ
 *
 * @version $Revision: 1.1 $
 */
public class JabberTransportChannel extends TcpTransportChannel {

    private static final Log log = LogFactory.getLog(JabberTransportChannel.class);

    private XMLInputFactory inputFactory;
    private BufferedInputStream in;


    public JabberTransportChannel() {
        super(new JabberWireFormat());
    }

    public JabberTransportChannel(URI remoteLocation) throws JMSException {
        super(new JabberWireFormat(), remoteLocation);
    }

    public JabberTransportChannel(URI remoteLocation, URI localLocation) throws JMSException {
        super(new JabberWireFormat(), remoteLocation, localLocation);
    }

    public JabberTransportChannel(TcpTransportServerChannel serverChannel, Socket socket, Executor executor) throws JMSException {
        super(serverChannel, new JabberWireFormat(), socket, executor);
    }
    public JabberTransportChannel(Socket socket, Executor executor) throws JMSException {
        super(new JabberWireFormat(), socket, executor);
    }

    public void run() {
        System.out.println("Jabber consumer thread starting");
        log.trace("Jabber consumer thread starting");
        int count = 0;

        try {
            if (inputFactory == null) {
                inputFactory = XMLInputFactory.newInstance();
            }
            XMLStreamReader reader = inputFactory.createXMLStreamReader(in);

            System.out.println("Reading start");
            Packet packet = getJabberWireFormat().readConnectionStart(reader);
            if (packet != null) {

                // lets send back the response
                System.out.println("sending start");
                send(packet);

                while (!isClosed()) {
                    if (isServerSide() && ++count > 500) {
                        count = 0;
                        Thread.yield();
                    }

                    if (!reader.hasNext()) {
                        System.out.println("End of stream");
                        stop();
                        break;
                    }
                    System.out.println("About to parse packet...");

                    packet = getJabberWireFormat().readPacket(reader);
                    System.out.println("#### read packet: " + packet);
                    if (packet != null) {
                        doConsumePacket(packet);
                    }
                }
            }
            stop();
        }
        catch (XMLStreamException e) {
            doClose(e);
        }
        catch (JMSException e) {
            doClose(e);
        }
    }

    public JabberWireFormat getJabberWireFormat() {
        return (JabberWireFormat) getWireFormat();
    }

    protected void initializeStreams() throws IOException {
        System.out.println("Creating input stream");
        this.in = new BufferedInputStream(socket.getInputStream(),8192);
        this.dataIn = new DataInputStream(in);

        System.out.println("creating output stream");
        TcpBufferedOutputStream buffOut = new TcpBufferedOutputStream(socket.getOutputStream(),8192);
        this.dataOut = new DataOutputStream(buffOut);

        System.out.println("Creating print writer...");
        PrintWriter writer = new PrintWriter(buffOut);
        //PrintWriter writer = new PrintWriter(System.out);
        getJabberWireFormat().setWriter(writer);
        System.out.println("Firing event");
        fireStatusEvent(new TransportStatusEvent(this,TransportStatusEvent.CONNECTED));
    }
}
