/*
 * Copyright (c) 2007-2008 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * This component and the accompanying materials are made available
 * under the terms of the License "Eclipse Public License v1.0"
 * which accompanies this distribution, and is available
 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
 *
 * Initial Contributors:
 * Nokia Corporation - initial contribution.
 *
 * Contributors:
 *
 * Description:  
 *
 */

package com.nokia.helium.scm.ant.actions;

import java.io.File;
import java.util.List;

import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmTag;
import org.apache.maven.scm.repository.ScmRepository;
import org.apache.tools.ant.BuildException;

import com.nokia.helium.scm.ant.types.TagSet;
import com.nokia.maven.scm.command.tags.TagsScmResult;
import com.nokia.maven.scm.manager.ExtendedScmManager;

/**
 * This action will tag current repository revision using a specific name.
 * 
 * <pre>
 * &lt;hlm:scm verbose="true" scmUrl="scm:${repo.type}:${repo.dir}/test1"&gt;
 *     &lt;hlm:tags baseDir="${repo.dir}/test1" reference="my.tags" /&gt;
 * &lt;/hlm:scm&gt;
 * </pre>
 *
 * @ant.type name="tags" category="SCM"
 */
public class TagsAction extends BaseDirectoryScmAction {

    private String reference;

    /**
     * Defines the id of the result type generated by the query.
     * @param reference the name of the reference to use.
     * @ant.not-required Only log result by default.
     */
    public void setReference(String reference) {
        this.reference = reference;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void execute(ScmRepository repository) throws ScmException {
        TagsScmResult result;
        try {
            ExtendedScmManager scmManager = (ExtendedScmManager) getTask()
                    .getScmManager();
            result = scmManager.tags(repository, new File(this.getBasedir()));
            if (!result.isSuccess()) {
                throw new BuildException("SCM tags action error: "
                        + result.getProviderMessage());
            }

            // Creating a TagSet
            List<ScmTag> tags = result.getTags();
            TagSet tagSet = new TagSet();
            tagSet.setProject(getProject());
            getTask().log("Tag list:");
            for (ScmTag tag : tags) {
                tagSet.createTag().setName(tag.getName());
                getTask().log(" * " + tag.getName());
            }
            // Creating new reference
            if (reference != null) {
                getTask().log("Creating reference: " + reference);
                getProject().addReference(reference, tagSet);
            }

        } catch (ScmException e) {
            throw new BuildException("SCM tags action failed: "
                    + e.getMessage());
        }

    }
}
