package org.apache.maven.cvslib;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache Maven" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache Maven", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * ====================================================================
 */

import java.io.InputStream;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
// commons imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
// maven imports
import org.apache.maven.changelog.AbstractChangeLogGenerator;
import org.apache.maven.project.Repository;
import org.apache.maven.util.AsyncStreamReader;
// ant imports
import org.apache.tools.ant.types.Commandline;

/**
 * A CVS implementation of the {@link org.apache.maven.changelog.ChangeLog}
 * interface.
 *
 * @task Check CVS exists first by running cvs -version instead of current hack
 * @author Glenn McAllister
 * @author <a href="mailto:jeff.martin@synamic.co.uk">Jeff Martin</a>
 * @author <a href="mailto:jason@zenplex.com">Jason van Zyl</a>
 * @author <a href="mailto:dion@multitask.com.au">dIon Gillard</a>
 * @author <a href="mailto:bodewig@apache.org">Stefan Bodewig</a>
 * @author <a href="mailto:peter@apache.org">Peter Donald</a>
 * @author <a href="mailto:pete-apache-dev@kazmier.com">Pete Kazmier</a>
 * @version 
 * $Id: CvsChangeLogGenerator.java,v 1.6 2003/04/11 18:53:19 bwalding Exp $
 */
class CvsChangeLogGenerator extends AbstractChangeLogGenerator
{
    /** Log */
    private static final Log LOG = LogFactory.getLog(CvsChangeLogGenerator.class);

    public static final int POS_SCM = 0;
    public static final int POS_SCM_TYPE = 1;
    public static final int POS_SCM_SUBTYPE = 2;
    public static final int POS_SCM_USERHOST = 3;
    public static final int POS_SCM_PATH = 4;
    public static final int POS_SCM_MODULE = 5;


    /**
     * @return the cvs command line to be executed.
     */
    protected Commandline getScmLogCommand()
    {
        String tokens[] = Repository.splitSCMConnection(getConnection());
        
        if (!tokens[POS_SCM_TYPE].equals("cvs"))
        {
            throw new IllegalArgumentException("repository connection string" + " does not specify 'cvs' as the scm");
        }
        
        Commandline command = new Commandline();

        command.setExecutable("cvs");
        command.createArgument().setValue("-d");
        // from format:
        // scm:cvs:pserver:anoncvs@cvs.apache.org:/home/cvspublic:jakarta-turbine-maven/src/plugins-build/changelog/
        // to format:
        // :pserver:anoncvs@cvs.apache.org:/home/cvspublic
        // use tokens 3+4+5
        String connectionBuffer = "";
        
        if (tokens[POS_SCM_SUBTYPE].equalsIgnoreCase("local"))
        {
            // use the local repository directory eg. '/home/cvspublic'
            connectionBuffer = tokens[POS_SCM_PATH];
        }
        else 
        {         
            if (tokens[POS_SCM_SUBTYPE].equalsIgnoreCase("lserver")) 
            {
                //create the cvsroot as the local socket cvsroot
                connectionBuffer = tokens[POS_SCM_USERHOST] + ":" + tokens[POS_SCM_PATH];
            }
            else 
            {
                //create the cvsroot as the remote cvsroot
                connectionBuffer =
                  ":" + tokens[POS_SCM_SUBTYPE] 
                + ":" + tokens[POS_SCM_USERHOST] 
                + ":" + tokens[POS_SCM_PATH];
            }
        }

        command.createArgument().setValue(connectionBuffer.toString());
        command.createArgument().setValue("log");

        if (dateRange != null)
        {
            command.createArgument().setValue(dateRange);
        }

        return command;
    }

    /** 
     * Construct the CVS command-line argument that is used to specify
     * the appropriate date range.
     * 
     * @param before The starting point.
     * @param to The ending point.
     * @return A string that can be used to specify a date to a scm
     * system.
     */
    protected String getScmDateArgument(Date before, Date to)
    {
        SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd");
        return "-d " + outputDate.format(before) + "<" + outputDate.format(to);
    }

    /** 
     * Handle ChangeLogParser IOExceptions.  
     * 
     * @param ioe The IOException thrown.
     * @throws IOException If the handler doesn't wish to handle the
     * exception.
     */
    protected void handleParserException(IOException ioe) throws IOException
    {
        if (ioe.getMessage().indexOf("CreateProcess") != -1 || ioe.getMessage().indexOf("cvs: not found") != -1)
        {
            // can't find CVS on Win32 or Linux...
            if (LOG.isWarnEnabled())
            {
                LOG.warn("Unable to find cvs executable. " + "Changelog will be empty");
            }
        }
        else
        {
            throw ioe;
        }
    }

    /**
     * Set the error stream for reading from cvs log. This stream will be read
     * on a separate thread.
     * @param is - an {@link java.io.InputStream}
     */
    public void setProcessErrorStream(InputStream is)
    {
        errorReader = new CvsAsyncErrorReader(is);
    }

    /**
     * A private AsyncStreamReader class that "swallows" the "cvs server:
     * Logging" lines.
     */
    private static class CvsAsyncErrorReader extends AsyncStreamReader
    {
        /**
         * The obvious constructor.
         *
         * @param anInputStream the input stream to consume
         */
        public CvsAsyncErrorReader(InputStream anInputStream)
        {
            super(anInputStream);
        }

        /**
         * If the line does not start with "cvs server: Logging", it's ok to
         * consume it.
         *
         * @param line the line to check
         * @return <code>true</code> if the line does not start with "cvs
         * server: Logging"
         */
        protected boolean okToConsume(String line)
        {
            return !line.startsWith("cvs server: Logging");
        }
    }
}
