/*
 * @(#)HttpResponse.java
 *
 * Copyright (c) 2001-2002 JScape
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JScape. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JScape.
 */
package com.jscape.inet.http;

import com.jscape.inet.mime.MimeException;
import com.jscape.inet.mime.MimeHeader;
import com.jscape.inet.mime.MimeMessage;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;


/**
 * Represents an HTTP response as returned by the HTTP server in response to an HTTP request.
 * <p>
 * Example Usage:
 * </p>
 * <p/>
 * <P>
 * <pre>
 * Http http = new Http();
 * HttpRequest request = new HttpRequest("http://www.myserver.com","GET");
 * HttpResponse response = http.getResponse(request);
 * </pre>
 * </p>
 */
public class HttpResponse
        extends MimeMessage
        implements Serializable {
    /**
     * Holds value of property responseCode.
     */
    private int responseCode;

    /**
     * Holds value of property httpVersion.
     */
    private String httpVersion;

    /**
     * Creates a new HttpResponse object.
     *
     * @param message the contents of the HTTP response
     *
     * @throws MimeException if a MIME related parsing error occurs
     */
    public HttpResponse(byte[] message)
            throws MimeException {
        super(message);
    }

    /**
     * Gets response code returned in HTTP response.
     *
     * @return HTTP response code
     */
    public int getResponseCode() {
        return this.responseCode;
    }

    /**
     * Sets response code returned in HTTP response.
     *
     * @param responseCode HTTP response code
     */
    protected void setResponseCode(int responseCode) {
        this.responseCode = responseCode;
    }

    /**
     * Gets HTTP version sent in response.
     *
     * @return HTTP version
     */
    public String getHttpVersion() {
        return this.httpVersion;
    }

    /**
     * Sets version returned in HTTP response.
     *
     * @param httpVersion the HTTP version
     */
    protected void setHttpVersion(String httpVersion) {
        this.httpVersion = httpVersion;
    }

    /**
     * Gets value of Content-Length header in HTTP response representing the
     * total number of bytes in HTTP response
     *
     * @return content length
     */
    public int getContentLength() {
        int contentLength = -1;
        MimeHeader header = getHeader("Content-Length");

        if (header != null) {
            contentLength = Integer.parseInt(header.getValue());
        }

        return contentLength;
    }

    /**
     * Gets value of Content-Type header in HTTP response
     *
     * @return content type
     */
    public String getContentType() {
        String contentType = null;
        MimeHeader header = getHeader("Content-Type");

        if (header != null) {
            contentType = header.getValue();
        }

        return contentType;
    }

    /**
     * Gets Last-Modified header from HTTP response representing the date the
     * content received was last modified.
     *
     * @return date last modified
     */
    public Date getLastModified() {
        MimeHeader header = getHeader("Last-Modified");

        if (header == null) {
            return null;
        } else {
            return new Date(getHeaderFieldDate(header.getValue()));
        }
    }

    /**
     * Gets Date header from HTTP response representing the date the response
     * was issued.
     *
     * @return date of response
     */
    public Date getDate() {
        MimeHeader header = getHeader("Date");

        if (header == null) {
            return null;
        } else {
            return new Date(getHeaderFieldDate(header.getValue()));
        }
    }

    /**
     * Gets the Expires header from HTTP response representing the date the
     * content is set to expire for caching purposes.
     *
     * @return content expiration date
     */
    public Date getExpires() {
        MimeHeader header = getHeader("Expires");

        if (header == null) {
            return null;
        } else {
            return new Date(getHeaderFieldDate(header.getValue()));
        }
    }

    /**
     * Converts date format provided by server to a long
     *
     * @param value the value of the header
     *
     * @return the date represented as a long
     */
    private long getHeaderFieldDate(String value) {
        try {
            DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");

            return df.parse(value).getTime();
        } catch (Throwable t) {
            return -1;
        }
    }

    /**
     * Gets all cookies sent back by HTTP server.
     *
     * @return an Enumeration of <code>HttpCookie</code>
     *
     * @throws MimeException if an error occurs while parsing HTTP headers
     */
    @SuppressWarnings("unchecked")
    public Enumeration getCookies()
            throws MimeException {
        Vector tmp = new Vector();

        for (int i = 0; i < headers.size(); ++i) {
            MimeHeader mh = (MimeHeader) headers.elementAt(i);
            mh.setFolding(false);

            if (mh.getName().equalsIgnoreCase("Set-Cookie")) {
                HttpCookie cookie = new HttpCookie();
                cookie.parse(mh.toString().getBytes(StandardCharsets.US_ASCII));
                tmp.addElement(cookie);
            }
        }

        return tmp.elements();
    }
}
