/**
 *
 * Magnolia SimpleMedia Module (http://www.openmindlab.com/lab/products/media.html)
 * Copyright(C) 2008-2010, Openmind S.r.l. http://www.openmindonline.it
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.sourceforge.openutils.mgnlmedia.playlist.pages;

import info.magnolia.cms.core.Content;
import info.magnolia.cms.i18n.I18nContentSupportFactory;
import info.magnolia.cms.util.ContentUtil;
import info.magnolia.cms.util.NodeDataUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.openutils.mgnlmedia.media.lifecycle.MediaModule;
import net.sourceforge.openutils.mgnlmedia.media.pages.MessagesTemplatedMVCHandler;
import net.sourceforge.openutils.mgnlmedia.media.tags.el.MediaEl;
import net.sourceforge.openutils.mgnlmedia.playlist.PlaylistConstants;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author dschivo
 */
public class PlaylistView extends MessagesTemplatedMVCHandler
{

    /**
     * Logger.
     */
    private Logger log = LoggerFactory.getLogger(PlaylistView.class);

    private String path;

    private PlaylistBean playlist;

    private String title;

    private String description;

    /**
     *
     */
    public PlaylistView(String name, HttpServletRequest request, HttpServletResponse response)
    {
        super(name, request, response);
    }

    /**
     * Sets the path.
     * @param path the path to set
     */
    public void setPath(String path)
    {
        this.path = path;
    }

    /**
     * Returns the playlist.
     * @return the playlist
     */
    public PlaylistBean getPlaylist()
    {
        return playlist;
    }

    /**
     * Sets the title.
     * @param title the title to set
     */
    public void setTitle(String title)
    {
        this.title = title;
    }

    /**
     * Sets the description.
     * @param description the description to set
     */
    public void setDescription(String description)
    {
        this.description = description;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String show()
    {
        if (StringUtils.isNotBlank(path))
        {
            Content node = ContentUtil.getContent(PlaylistConstants.REPO, path);
            if (node != null)
            {
                playlist = new PlaylistBean();
                playlist.setUuid(node.getUUID());
                playlist.setHandle(node.getHandle());
                playlist.setTitle(NodeDataUtil.getString(node, "title"));
                playlist.setDescription(NodeDataUtil.getString(node, "description"));
                List<PlaylistEntryBean> entries = new ArrayList<PlaylistEntryBean>();

                Collection<Content> children = node.getChildren(PlaylistConstants.PLAYLIST_ENTRY);
                for (Content subNode : children)
                {
                    String mediaUUID = NodeDataUtil.getString(subNode, "media");
                    Content media = ContentUtil.getContentByUUID(MediaModule.REPO, mediaUUID);
                    if (media != null)
                    {
                        PlaylistEntryBean entry = new PlaylistEntryBean();
                        entry.setHandle(subNode.getHandle());
                        entry.setMedia(media.getUUID());
                        entry.setThumbnail(MediaEl.thumbnail(media));
                        entry.setType(NodeDataUtil.getString(media, "type"));
                        entry.setTitle(I18nContentSupportFactory
                            .getI18nSupport()
                            .getNodeData(media, "title")
                            .getString());
                        entry.setDescription(I18nContentSupportFactory.getI18nSupport().getNodeData(
                            media,
                            "description").getString());
                        entry
                            .setTags(I18nContentSupportFactory.getI18nSupport().getNodeData(media, "tags").getString());
                        entries.add(entry);
                    }
                    else
                    {
                        log.warn(
                            "Node {} referenced by entry {} of playlist {} does not exist in media repository",
                            new Object[]{mediaUUID, subNode.getName(), playlist.getHandle() });
                    }
                }
                playlist.setEntries(entries);
            }
            else
            {
                log.warn("Node {} does not exist in playlist repository", path);
            }
        }
        return super.show();
    }

    public String save()
    {
        Content node = ContentUtil.getContent(PlaylistConstants.REPO, path);
        if (node != null)
        {
            try
            {
                NodeDataUtil.getOrCreateAndSet(node, "title", title);
                NodeDataUtil.getOrCreateAndSet(node, "description", description);
                if (MediaEl.module().isSingleinstance())
                {
                    node.getMetaData().setActivated();
                }
                node.save();
            }
            catch (RepositoryException e)
            {
            }
        }
        return null;
    }
}
