/** 
 * 
 * Copyright 2004 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.codehaus.activemq.transport.http;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.activemq.io.TextWireFormat;
import org.codehaus.activemq.message.Packet;
import org.codehaus.activemq.util.Callback;
import org.codehaus.activemq.util.ExceptionTemplate;
import org.codehaus.activemq.util.JMSExceptionHelper;

import javax.jms.JMSException;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @version $Revision: 1.3 $
 */
public class HttpTransportChannel extends HttpTransportChannelSupport {
    private static final Log log = LogFactory.getLog(HttpTransportChannel.class);
    private URL url;
    private HttpURLConnection sendConnection;
    private HttpURLConnection receiveConnection;


    public HttpTransportChannel(TextWireFormat wireFormat, String remoteUrl) throws MalformedURLException {
        super(wireFormat, remoteUrl);
        url = new URL(remoteUrl);
    }

    public void asyncSend(Packet packet) throws JMSException {
        try {
            HttpURLConnection connection = getSendConnection();
            String text = getWireFormat().toString(packet);
            Writer writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(text);
            writer.flush();
            int answer = connection.getResponseCode();
            if (answer != HttpURLConnection.HTTP_OK) {
                throw new JMSException("Failed to post packet: " + packet + " as response was: " + answer);
            }
        }
        catch (IOException e) {
            throw JMSExceptionHelper.newJMSException("Could not post packet: " + packet + " due to: " + e, e);
        }
    }

    public void stop() {
        ExceptionTemplate template = new ExceptionTemplate();
        if (sendConnection != null) {
            template.run(new Callback() {
                public void execute() throws Throwable {
                    sendConnection.disconnect();
                }
            });
        }
        if (receiveConnection != null) {
            template.run(new Callback() {
                public void execute() throws Throwable {
                    receiveConnection.disconnect();
                }
            });
        }
        super.stop();
        Throwable firstException = template.getFirstException();
        if (firstException != null) {
            log.warn("Failed to shut down cleanly: " + firstException, firstException);
        }
    }

    public boolean isMulticast() {
        return false;
    }

    public void run() {
        log.trace("HTTP GET consumer thread starting for clientID: " + getClientID());
        String remoteUrl = getRemoteUrl();
        while (!getClosed().get()) {
            try {
                HttpURLConnection connection = getReceiveConnection();
                int answer = connection.getResponseCode();
                if (answer != HttpURLConnection.HTTP_OK) {
                    if (answer == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {
                        log.trace("GET timed out");
                    }
                    else {
                        log.warn("Failed to perform GET on: " + remoteUrl + " as response was: " + answer);
                    }
                }
                else {
                    Packet packet = getWireFormat().readPacket(new DataInputStream(connection.getInputStream()));
                    //Packet packet = getWireFormat().fromString(connection.getContent().toString());
                    if (packet == null) {
                        log.warn("Received null packet from url: " + remoteUrl);
                    }
                    else {
                        doConsumePacket(packet);
                    }
                }
            }
            catch (Exception e) {
                if (!getClosed().get()) {
                    log.warn("Failed to perform GET on: " + remoteUrl + " due to: " + e, e);
                }
                else {
                    log.trace("Caught error after closed: " + e, e);
                }
            }
        }
    }


    // Implementation methods
    //-------------------------------------------------------------------------
    protected synchronized HttpURLConnection getSendConnection() throws IOException {
        sendConnection = (HttpURLConnection) url.openConnection();
        sendConnection.setDoOutput(true);
        sendConnection.setRequestMethod("POST");
        configureConnection(sendConnection);
        sendConnection.connect();
        return sendConnection;
    }

    protected synchronized HttpURLConnection getReceiveConnection() throws IOException {
        receiveConnection = (HttpURLConnection) url.openConnection();
        receiveConnection.setDoOutput(false);
        receiveConnection.setDoInput(true);
        receiveConnection.setRequestMethod("GET");
        configureConnection(receiveConnection);
        receiveConnection.connect();
        return receiveConnection;
    }


    protected void configureConnection(HttpURLConnection connection) {
        String clientID = getClientID();
        if (clientID != null) {
            connection.setRequestProperty("clientID", clientID);
            //connection.addRequestProperty("clientID", clientID);
        }
    }
    
	public void forceDisconnect() {
	    // TODO: implement me.
		throw new RuntimeException("Not yet Implemented.");
	}
    
}
