/*
 * 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.io.PrintWriter;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import javax.emb.MediaEntityLocal;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import emb.sample.MediaSampleException;
import emb.sample.session.MediaSampleSessionLocal;

/**
 * This servlet is intent to control requests to loading the sample media to the
 * database.
 */
public class LoadSampleMedia extends BaseSampleServlet {

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

    /**
     * default dir where sample are stored
     */
    private static final String SAMPLES_DIR = "/samples/";

    /**
     * The sample info file
     */
    private static final String SAMPLES_PROPERTIES = "samples.properties";

    /**
     * @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 {

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

        getServletConfig().getServletContext().getRequestDispatcher("/jsps/header.jsp").include(request, response);

        PrintWriter out = response.getWriter();
        out.println("<h2>Initializing Sample DataBase</h2>");

        // Create Samples in DB
        try {

            MediaSampleSessionLocal session = getSession(request);

            // get all MEB stored with the same Partial Desc
            if (session.getMediaList().length > 0) {
                out.println("<h2>Samples already loaded... -> removing default Media</h2>");
                session.removeDefaultMedia();
                out.flush();
            }

            out.println("<h2>Adding new Samples to the DataBase...</h2>");
            out.println("<ul>");
            out.flush();

            // get the properties stream
            InputStream propStream = getServletContext().getResourceAsStream(SAMPLES_DIR + SAMPLES_PROPERTIES);

            if (propStream != null) {
                try {

                    // new properties
                    Properties prop = new Properties();

                    // load properties from stream
                    prop.load(propStream);

                    List sortList = new LinkedList(prop.keySet());

                    Collections.sort(sortList);

                    for (Iterator i = sortList.iterator(); i.hasNext();) {

                        // Get class name and file extension
                        String sampleNameWSuffix = (String) i.next();

                        if (sampleNameWSuffix.endsWith(".file")) {
                            String sampleName = getPrefixFileName(sampleNameWSuffix);

                            String sampleFile = prop.getProperty(sampleName + ".file");
                            String sampleDesc = prop.getProperty(sampleName + ".desc");
                            String sampleShowS = prop.getProperty(sampleName + ".show");
                            boolean sampleShow = Boolean.valueOf(sampleShowS).booleanValue();

                            byte status = MediaSampleSessionLocal.DONT_SHOW;
                            if (sampleShow) {
                                status = MediaSampleSessionLocal.SHOW_IN_LIST;
                            }

                            createNewSample(session, out, sampleFile, sampleDesc, getServletContext()
                                    .getResourceAsStream(SAMPLES_DIR + sampleFile), sampleName, status);

                        }
                    }

                } catch (IOException e) {
                    // error while loading properties
                    new MediaSampleException("Unable to load sample properties due to : " + e.getLocalizedMessage(), e);
                }
            } else {
                // error while open properties stream
                new MediaSampleException("Unable to load sample properties due to : " + SAMPLES_PROPERTIES
                        + " has no been found");
            }

            out.println("</ul>");
            out.println("<h2>Media loaded.</h2>");

            getServletConfig().getServletContext().getRequestDispatcher("/jsps/footer.jsp").include(request, response);

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

    }

    /**
     * Create a MEB sample with given param
     *
     * @param session the session which control medi creation
     * @param out out writer
     * @param name name of the MEB
     * @param description description desc of the MEB
     * @param contentStream contentStream content of the EMB
     * @param registeredName the name to access to it
     * @param status status is ones of {@link MediaSampleSessionLocal#DONT_SHOW},
     *            {@link MediaSampleSessionLocal#SHOW_IN_LIST},
     *            {@link MediaSampleSessionLocal#USER_ADDED}
     * @return the media entity
     */
    private MediaEntityLocal createNewSample(MediaSampleSessionLocal session, PrintWriter out, String name,
            String description, InputStream contentStream, String registeredName, byte status) {
        // Create MEB sample
        out.println("<li>");
        MediaEntityLocal meb = null;
        try {

            meb = session.createMediaEntity(contentStream, name, description, status, registeredName);

            out.println(name);

        } catch (Throwable e) {

            try {
                if (meb != null) {
                    meb.remove();
                }
            } catch (Throwable e1) {
                // do nothing
            }

            meb = null;

            String err = "Error while creating sample \"" + name + "\" : " + e.getLocalizedMessage();
            out.println("<span class=\"error\">" + err + "</span>");
            // System.err.println("LoadSampleMedia : " + err);
            // e.printStackTrace();
        }
        out.println("</li>");
        out.flush();
        return meb;
    }

    /**
     * Get name of a file name without extension
     *
     * @param name name of the file
     * @return file name without extension
     */
    public static String getPrefixFileName(String name) {
        int lastDotPosition = name.lastIndexOf('.');

        if (lastDotPosition == -1) {
            return name;
        }
        return name.substring(0, lastDotPosition);

    }
}
