/**
 *
 * 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.media.setup;

import info.magnolia.cms.core.Content;
import info.magnolia.cms.core.NodeData;
import info.magnolia.cms.core.search.Query;
import info.magnolia.cms.core.search.QueryManager;
import info.magnolia.cms.core.search.QueryResult;
import info.magnolia.module.InstallContext;
import info.magnolia.module.delta.Task;
import info.magnolia.module.delta.TaskExecutionException;

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

import javax.jcr.RepositoryException;
import javax.jcr.nodetype.ConstraintViolationException;

import net.sourceforge.openutils.mgnlmedia.media.configuration.MediaConfigurationManager;
import net.sourceforge.openutils.mgnlmedia.media.lifecycle.MediaModule;
import net.sourceforge.openutils.mgnlmedia.media.types.impl.BaseTypeHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author fgiust
 * @version $Id: MoveOriginalNodeTask.java 1845 2010-02-07 11:02:00Z fgiust $
 */
public class MoveOriginalNodeTask implements Task
{

    /**
     * Logger.
     */
    private Logger log = LoggerFactory.getLogger(this.getClass());

    public String getName()
    {
        return "file store nodedata name updater";
    }

    public String getDescription()
    {
        return "update custom nodedata names (where original files are stored) to \"original\"";
    }

    public void execute(InstallContext installContext) throws TaskExecutionException
    {
        QueryManager mgr = installContext.getHierarchyManager(MediaModule.REPO).getQueryManager();
        try
        {
            reset(mgr, "image", "image");
            reset(mgr, "video", "video");
            reset(mgr, "audio", "audio");
        }
        catch (RepositoryException ex)
        {
            log.error(ex.getMessage(), ex);
        }
    }

    private void reset(QueryManager queryManager, String type, String nodedataOldName) throws RepositoryException
    {
        Query query = queryManager.createQuery("//*[" + nodedataOldName + " and type='" + type + "']", Query.XPATH);
        QueryResult queryResult = query.execute();
        Collection<Content> medias = queryResult.getContent(MediaConfigurationManager.MEDIA.getSystemName());
        for (Content media : medias)
        {
            NodeData nd = media.getNodeData(nodedataOldName);
            if (nd.getValue() != null)
            {
                NodeData ndNew = media.createNodeData(BaseTypeHandler.ORGINAL_NODEDATA_NAME, nd.getValue());
                for (String attributeName : ((List<String>) nd.getAttributeNames()))
                {
                    try
                    {
                        ndNew.setAttribute(attributeName, nd.getAttribute(attributeName));
                    }
                    catch (ConstraintViolationException ex)
                    {
                        // go on
                    }
                }
                nd.delete();
            }
            // media.deleteNodeData(nd.getName());
            media.save();
        }
    }
}