/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2005 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Initial developer(s): Brice Ruzand
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package emb.sample.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.emb.GenericMediaFormat;
import javax.emb.MediaEntityLocal;
import javax.emb.MediaFormat;
import javax.emb.MediaFormatRegistry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import emb.sample.session.MediaSampleSessionLocal;

/**
 * Generate an HTML web page to present the media
 *
 * @author Brice Ruzand
 */
public class UploadSampleMedia extends BaseSampleServlet {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 3762250859580634161L;

    /**
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     * @inheritDoc
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {

            response.setContentType("text/html;charset=ISO-8859-1");

            StringPrinter fromatSupported = new StringPrinter();
            fromatSupported.println("<ul>");
            for (Iterator i = MediaFormatRegistry.SINGLETON.getFileExtensions(); i.hasNext();) {
                String fileExt = (String) i.next();
                MediaFormat format = MediaFormatRegistry.SINGLETON.lookup(fileExt);
                if (!(format == null || format instanceof GenericMediaFormat)) {
                    fromatSupported.println("<li>" + fileExt + " : " + MediaFormatRegistry.SINGLETON.lookup(fileExt)
                            + "</li>");
                }
            }
            fromatSupported.println("</ul>");

            request.setAttribute("fromatSupported", fromatSupported);
            getServletConfig().getServletContext().getRequestDispatcher("/jsps/uploadForm.jsp").include(request, response);

        } catch (Throwable e) {
            exceptionHandler(e, getClass(), request, response);
        }
    }

    /**
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     * @inheritDoc
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {

            String mediaDesc = "";
            String mediaName = "";
            String mediaUrl = "";
            InputStream mediaInputStream = null;

            // Create a new file upload handler
            DiskFileUpload upload = new DiskFileUpload();

            // Parse the request
            List /* FileItem */items = upload.parseRequest(request);

            // Process the uploaded items
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equals("desc")) {
                        mediaDesc = item.getString();
                    }
                    if (item.getFieldName().equals("url")) {
                        mediaUrl = item.getString();
                    }
                } else {
                    if (item.getFieldName().equals("file")) {
                        mediaInputStream = item.getInputStream();
                        mediaName = item.getName();
                    }
                }
            }

            MediaSampleSessionLocal session = getSession(request);

            MediaEntityLocal meb = null;
            if (mediaUrl != null && mediaUrl.length() > 0) {
                // meb = createNewSample(mediaUrl, mediaDesc);
                meb = session.createMediaEntity(new URL(mediaUrl), mediaDesc, MediaSampleSessionLocal.USER_ADDED);
            } else if (mediaInputStream != null && mediaName != null && mediaName.length() > 0) {
                meb = session.createMediaEntity(mediaInputStream, mediaName, mediaDesc,
                        MediaSampleSessionLocal.USER_ADDED, null);
            }

            if (meb != null) {

                // forward onto the retrieve servlet
                request.setAttribute("identity", meb.getPrimaryKey());
                this.getServletContext().getRequestDispatcher(RETRIEVE_SERVLET).forward(request, response);

            } else {

                StringPrinter workspaceContent = new StringPrinter();
                workspaceContent.println("<h2>Missing information to add media</h2>");
                workspaceContent.println("There were some missing information to add media, please retry.");
                request.setAttribute("workspaceContent", workspaceContent);
                this.getServletContext().getRequestDispatcher(TEMPLATE_JSP).forward(request, response);

            }

        } catch (Throwable e) {
            exceptionHandler(e, getClass(), request, response);
        }
    }

}
