package org.apache.maven.xdoc.util;

/* ====================================================================
 *   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 java.util.ArrayList;
import java.util.List;

import org.apache.maven.util.EnhancedStringTokenizer;

/**
 * Utility class to manage SCM informations.
 * NOTE: This is very CVS specific, but I would like to try additional SCM
 * package like subversion ASAP.
 *
 * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
 * @author <a href="mailto:aheritier@apache.org">Arnaud Heritier</a>
 * @version $Id$
 */
public final class ScmUtil
{

    /**
     * Get the SCM type.
     * 
     * @param scmConnection the scm connection to analyse.
     * @return the scm type : cvs, svn , ...
     */
    public String getScmType(final String scmConnection)
    {
        if (isValid(scmConnection))
        {
            return splitSCMConnection(scmConnection)[1];
        }
        return null;
    }

    /**
     * Get cvs root.
     * 
     * @param scmConnection the scm connection to analyse.
     * @return CVS root.
     */
    public String getCvsRoot(String scmConnection)
    {
        if (isValid(scmConnection))
        {
            return getCvsRoot(scmConnection, "");
        }

        return null;
    }

    /**
     * Get cvs server. Used in
     * xdocs/src/plugin-resources/templates/cvs-usage.xml.
     * 
     * @param conn six token connection string
     * @return CVS module.
     */
    public String getCvsServer(String conn)
    {
        String[] tokens = splitSCMConnection(conn);
        if (!tokens[1].equals("cvs"))
        {
            return "";
        }

        if (tokens[3].indexOf('@') >= 0)
        {
            return tokens[3].substring(tokens[3].indexOf('@') + 1);
        }
        else
        {
            return tokens[3];
        }
    }

    /**
     * Get cvs root. Used in xdocs/src/plugin-resources/templates/cvs-usage.xml.
     * 
     * @param conn six token connection string
     * @param username username override if non-empty.
     * @return CVS root.
     */
    public String getCvsRoot(String conn, String username)
    {
        String[] tokens = splitSCMConnection(conn);

        if (!tokens[1].equals("cvs"))
        {
            return "";
        }

        if (tokens[3].indexOf('@') >= 0)
        {
            if (username.length() == 0)
            {
                username = tokens[3].substring(0, tokens[3].indexOf('@'));
            }
            tokens[3] = username + "@" + tokens[3].substring(tokens[3].indexOf('@') + 1);
        }
        String result = ":" + tokens[2] + ":" + tokens[3] + ":" + tokens[4];
        return result;
    }

    /**
     * Get cvs module. Used in
     * xdocs/src/plugin-resources/templates/cvs-usage.xml.
     * 
     * @param conn six token connection string
     * @return CVS module.
     */
    public String getCvsModule(String conn)
    {
        if (isValid(conn))
        {

            String[] tokens = splitSCMConnection(conn);
            if (!tokens[1].equals("cvs"))
            {
                return "";
            }
            return tokens[5];
        }

        return null;
    }

    /**
     * Splits an SCM string into parts.
     * 
     * @param connection
     * @return A string array of SCM parts
     */
    public String[] splitSCMConnection(String connection)
    {
        if (connection == null)
        {
            throw new NullPointerException("repository connection is null");
        }

        if (connection.length() < 4)
        {
            throw new IllegalArgumentException("repository connection is too short");
        }

        if (!connection.startsWith("scm"))
        {
            throw new IllegalArgumentException("repository connection must start with scm[delim]");
        }

        String delimiter = "" + connection.charAt(3);

        EnhancedStringTokenizer tok = new EnhancedStringTokenizer(connection, delimiter);

        String[] tokens = tokenizerToArray(tok);

        // for a valid repository, it should be scm:<provider> at least
        if (tokens.length >= 1 && tokens[1].equals("cvs"))
        {
            if (tokens.length != 6)
            {
                throw new IllegalArgumentException(
                    "cvs repository connection string doesn't contain six tokens");
            }
        }
        return tokens;
    }

    /**
     * Converts a tokenizer to an array of strings FIXME: This should be in a
     * string util class.
     * 
     * @param tok
     * @return String[]
     */
    public String[] tokenizerToArray(EnhancedStringTokenizer tok)
    {
        List l = new ArrayList();
        while (tok.hasMoreTokens())
        {
            l.add(tok.nextToken());
        }
        return (String[]) l.toArray(new String[l.size()]);
    }

    /**
     * Simple check for a value in the POM. Due to the Jelly swizzling fields that aren't set come
     * out as empty strings. This will not be required when the new lazy evaluation mechanism is put
     * in place.
     * 
     * @param value POM value to test.
     * @return Is the value valid.
     */
    protected boolean isValid(String value)
    {
        if (value != null && !value.trim().equals(""))
        {
            return true;
        }

        return false;
    }
}
