/** 
 * 
 * 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.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
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.JMSExceptionHelper;

import javax.jms.JMSException;
import java.io.DataInputStream;
import java.io.IOException;

/**
 * A HTTP {@link org.codehaus.activemq.transport.TransportChannel} which uses the
 * <a href="http://jakarta.apache.org/commons/httpclient/">commons-httpclient</a> library
 *
 * @version $Revision: 1.3 $
 */
public class HttpClientTransportChannel extends HttpTransportChannelSupport {
    private static final Log log = LogFactory.getLog(HttpClientTransportChannel.class);

    private HttpClient sendHttpClient;
    private HttpClient receiveHttpClient;

    public HttpClientTransportChannel(TextWireFormat wireFormat, String remoteUrl) {
        super(wireFormat, remoteUrl);
    }

    public void asyncSend(Packet packet) throws JMSException {
        PostMethod httpMethod = new PostMethod(getRemoteUrl());
        configureMethod(httpMethod);
        httpMethod.setRequestBody(getWireFormat().toString(packet));
        try {
            int answer = getSendHttpClient().executeMethod(httpMethod);
            if (answer != HttpStatus.SC_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 boolean isMulticast() {
        return false;
    }

    public void run() {
        log.trace("HTTP GET consumer thread starting for clientID: " + getClientID());
        HttpClient httpClient = getReceiveHttpClient();
        String remoteUrl = getRemoteUrl();
        while (!getClosed().get()) {
            GetMethod httpMethod = new GetMethod(remoteUrl);
            configureMethod(httpMethod);
            try {
                int answer = httpClient.executeMethod(httpMethod);
                if (answer != HttpStatus.SC_OK) {
                    if (answer == HttpStatus.SC_REQUEST_TIMEOUT) {
                        log.info("GET timed out");
                    }
                    else {
                        log.warn("Failed to perform GET on: " + remoteUrl + " as response was: " + answer);
                    }
                }
                else {
                    Packet packet = getWireFormat().readPacket(new DataInputStream(httpMethod.getResponseBodyAsStream()));
                    if (packet == null) {
                        log.warn("Received null packet from url: " + remoteUrl);
                    }
                    else {
                        doConsumePacket(packet);
                    }
                }
            }
            catch (IOException e) {
                log.warn("Failed to perform GET on: " + remoteUrl + " due to: " + e, e);
            }
        }
    }

    // Properties
    //-------------------------------------------------------------------------
    public HttpClient getSendHttpClient() {
        if (sendHttpClient == null) {
            sendHttpClient = createHttpClient();
        }
        return sendHttpClient;
    }

    public void setSendHttpClient(HttpClient sendHttpClient) {
        this.sendHttpClient = sendHttpClient;
    }

    public HttpClient getReceiveHttpClient() {
        if (receiveHttpClient == null) {
            receiveHttpClient = createHttpClient();
        }
        return receiveHttpClient;
    }

    public void setReceiveHttpClient(HttpClient receiveHttpClient) {
        this.receiveHttpClient = receiveHttpClient;
    }

    // Implementation methods
    //-------------------------------------------------------------------------
    protected HttpClient createHttpClient() {
        return new HttpClient();
    }

    protected void configureMethod(HttpMethod method) {
        String clientID = getClientID();
        if (clientID != null) {
            method.setRequestHeader("clientID", clientID);
        }
    }
    
	public void forceDisconnect() {
	    // TODO: implement me.
		throw new RuntimeException("Not yet Implemented.");
	}
    
}
