package org.apache.maven.release;

/* ====================================================================
 *   Copyright 2001-2004 The Apache Software Foundation.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 * ====================================================================
 */

import org.apache.commons.io.FileUtils;
import org.apache.maven.MavenConstants;
import org.apache.maven.project.Project;
import org.apache.maven.util.HttpUtils;
import org.dom4j.Node;

import java.io.File;
import java.util.Iterator;

/**
 *
 *
 * @author <a href="mailto:jason@zenplex.com">Jason van Zyl</a>
 *
 * @version $Id$
 */
public class SnapshotResolver
    extends AbstractPomTransformer
{
    // -------------------------------------------------------------------------
    // Accessors
    // -------------------------------------------------------------------------

    public String selectNodesXPathExpression()
    {
        return "/project/dependencies/dependency[version='SNAPSHOT']";
    }

    public String selectNodeXPath()
    {
        return "version";
    }

    public String getNodeContent( Node node )
        throws Exception
    {
        String timestampVersion = "SNAPSHOT";

        Node idNode = node.selectSingleNode( "id" );

        String groupId;
        String artifactId;
        String artifactType = "jar";

        if ( idNode != null )
        {
            groupId = idNode.getText();
            artifactId = groupId;
        }
        else
        {
            Node artifactIdNode = node.selectSingleNode( "artifactId" );
            Node groupIdNode = node.selectSingleNode( "groupId" );

            groupId = groupIdNode.getText();
            artifactId = artifactIdNode.getText();
        }

        Node typeIdNode = node.selectSingleNode( "type" );

        if ( typeIdNode != null )
        {
            artifactType = typeIdNode.getText();
        }

        // Now we need to attempt to find the the actual timestamp
        // version for this dependency.

        // Variables are being stored as ConstantExpressions ...

        Project project = (Project) getVariables().get( MavenConstants.MAVEN_POM );
        File snapshotVersionFile = new File( getProject().getParentFile(), artifactId + "-snapshot-version" );

        for ( Iterator i = project.getContext().getMavenRepoRemote().iterator(); i.hasNext(); )
        {
            String remoteRepo = (String) i.next();
            String url = remoteRepo + "/" + groupId + "/" + artifactType + "s/" + artifactId + "-snapshot-version";
           
            try
            {
                HttpUtils.getFile( url,
                                   snapshotVersionFile,
                                   true, // ignore errors
                                   false, // use timestamps
                                   (String) getVariables().get( MavenConstants.PROXY_HOST ), // proxy host
                                   (String) getVariables().get( MavenConstants.PROXY_PORT ), // proxy port
                                   (String) getVariables().get( MavenConstants.PROXY_USERNAME ), // proxy user name
                                   (String) getVariables().get( MavenConstants.PROXY_PASSWORD ) // proxy password
                );
            }
            catch ( Exception e )
            {
                // Either doesn't exist, or we have a network problem. In
                // either event we can't update the version field.
                System.out.println( "Can't retrieve snapshot version file: " + e.getLocalizedMessage() );
            }

            if ( snapshotVersionFile.exists() )
            {
                timestampVersion = FileUtils.readFileToString( snapshotVersionFile, null );
            }
        }

        return timestampVersion;
    }

    public void transformNode( Node node )
        throws Exception
    {
        Node version = node.selectSingleNode( selectNodeXPath() );
        version.setText( getNodeContent( node ) );
    }

    public Node getTransformedNode( Node node )
        throws Exception
    {
        Node transformedNode = (Node) node.clone();
        Node version = transformedNode.selectSingleNode( selectNodeXPath() );
        version.setText( getNodeContent( transformedNode ) );

        return transformedNode;
    }
}
