/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.cms.dispatcher;

import com.arsdigita.bebop.parameters.BigDecimalParameter;
import com.arsdigita.bebop.parameters.NotNullValidationListener;
import com.arsdigita.cms.BinaryAsset;
import com.arsdigita.cms.Asset;
import com.arsdigita.dispatcher.DispatcherHelper;
import com.arsdigita.dispatcher.RequestContext;
import com.arsdigita.domain.DataObjectNotFoundException;
import com.arsdigita.domain.DomainObjectFactory;
import com.arsdigita.mimetypes.MimeType;
import com.arsdigita.persistence.OID;
import com.arsdigita.util.Assert;
import com.arsdigita.toolbox.ui.OIDParameter;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

class BaseAsset extends ResourceHandlerImpl {
    public static final String versionId = "$Id: //cms/dev/src/com/arsdigita/cms/dispatcher/BaseAsset.java#8 $ by $Author: dan $, $DateTime: 2004/05/10 10:32:44 $";

    private static final Logger s_log = Logger.getLogger(BaseAsset.class);

    public final static String ASSET_ID = "asset_id";
    public static final String OID_PARAM = "oid";

    private final static String s_defaultName = "File";

    private static final BigDecimalParameter s_assetId;
    private static final OIDParameter s_oid;

    static {
        s_assetId = new BigDecimalParameter(ASSET_ID);
        s_oid = new OIDParameter(OID_PARAM);
        //s_assetId.addParameterListener(new NotNullValidationListener());
    }

    private final boolean m_download;

    protected BaseAsset(boolean download) {
        m_download = download;
    }

    /**
     * Sets RFC2183 governed Contnet-Disposition header to supply filename to
     * client. See section 19.5.1 of RFC2616 for interpretation of
     * Content-Disposition in HTTP.
     */
    private void setFilenameHeader(HttpServletResponse response,
                                   BinaryAsset asset) {
        String filename = asset.getName();
        if (filename == null) { filename = s_defaultName; }


        // quote the file name to deal with any special 
        // characters in the name of the file
        StringBuffer quotedString = new StringBuffer("\"");
        quotedString.append(filename).append("\"");

        response.setHeader("Content-Disposition", 
                           "attachment; filename=" + quotedString.toString());
    }

    private void setHeaders(HttpServletResponse response,
                              BinaryAsset asset) {
        setFilenameHeader(response, asset);

        Long contentLength = new Long(asset.getSize());
        response.setContentLength(contentLength.intValue());

        MimeType mimeType = asset.getMimeType();

        if (m_download || mimeType == null) {
            // Section 19.5.1 of RFC2616 says this implies download
            // instead of view
            response.setContentType("application/octet-stream");
        } else {
            response.setContentType(mimeType.getMimeType());
        }

        DispatcherHelper.cacheForWorld(response);
    }

    private void send(HttpServletResponse response,
                        BinaryAsset asset) throws IOException {
        // Stream the blob.
        OutputStream out = response.getOutputStream();
        try {
            asset.writeBytes(out);
        } finally {
            out.close();
        }
    }

    public final void dispatch(HttpServletRequest request,
                               HttpServletResponse response,
                               RequestContext actx) 
        throws IOException, ServletException {

        // Fetch and validate the image ID.
        OID oid = (OID)s_oid.transformValue(request);
        BigDecimal assetId = (BigDecimal) s_assetId.transformValue(request);
        if ( assetId == null && oid == null ) {
            throw new ServletException(ASSET_ID + " or " + OID_PARAM + 
                                       " is required.");
        } else if ( assetId != null && oid != null ) {
            throw new ServletException(ASSET_ID + " or " + OID_PARAM + 
                                       " must not both be specified.");
        }
        if (oid == null) {
            oid = new OID(Asset.BASE_DATA_OBJECT_TYPE, assetId);
        }

        BinaryAsset asset = null;
        try {
            Asset a = (Asset)
                DomainObjectFactory.newInstance(oid);

            if (a instanceof BinaryAsset) {
                asset = (BinaryAsset) a;
            } else {
                if (s_log.isInfoEnabled()) {
                    s_log.info("Asset " + oid + " is not a BinaryAsset");
                }
            }
            // Not until permissions are properly assigned to assets
            //checkUserAccess(request, response, actx, asset);
        } catch (DataObjectNotFoundException nfe) {
            if (s_log.isInfoEnabled()) {
                s_log.info("no asset with oid " + oid, nfe);
            }
        }

        if (asset == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                               "No asset with ID " + assetId);
            return;
        }

        setHeaders(response, asset);
        send(response, asset);
    }
}
