package org.apache.maven.changes;

/* ====================================================================
 *   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.
 * ====================================================================
 */

/**
 * @author <a href="mailto:vmassol@apache.org">Vincent Massol</a>
 *
 * @version $Id$
 */
public class IssueFinder
{
    /**
     * @param trackerURL the issue tracker URL (this is supposed to be the 
     *        value of &lt;issueTrackingUrl&gt; found in the POM.
     * @param issue the issue reference
     * @param template the template string. Allowed template patterns are 
     *        <code>%URL%</code> and <code>%ISSUE%</code>. They will be 
     *        replaced by the base tracker URL extracted from trackerURL and 
     *        by the issue reference.
     * @return The URL of the issue.
     */
    public static String getIssueURL(String trackerURL, String issue, 
        String template)
    {
        // Find base URL of issue tracker
        String baseURL;
        int pos = trackerURL.lastIndexOf("/");
        if (pos > 0) {
            baseURL = trackerURL.substring(0, pos);
        } else {
            throw new RuntimeException("Failed to extract tracker URL from ["
                + trackerURL + "]");
        }

        // Use template to construct issue URL
        String issueURL = replace(template, "%URL%", baseURL);
        issueURL = replace(issueURL, "%ISSUE%", issue);

        return issueURL;
    }   

    /**
     * @param original the original template
     * @param oldPattern the pattern to replace
     * @param newPattern the new pattern
     * @return the modified template string with patterns applied
     */
    public static final String replace(String original, String oldPattern,
        String newPattern)
    {
        int index, oldIndex;
        StringBuffer buffer = new StringBuffer();
        
        if((index = original.indexOf(oldPattern)) != -1) {
            oldIndex = 0;
            while((index = original.indexOf(oldPattern, oldIndex)) != -1) {
                buffer.append(original.substring(oldIndex, index));
                buffer.append(newPattern);
                oldIndex = index + oldPattern.length();
            }
            buffer.append(original.substring(oldIndex));
            original = buffer.toString();
        }
        return original;
    }

}