package org.apache.maven.artifact.deployer;

/* ====================================================================
 *   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.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.maven.wagon.events.TransferEvent;
import org.apache.maven.wagon.events.TransferListener;

/**
 * Bootstrap download progress meter.
 *
 * @author <a href="mailto:brett@apache.org">Brett Porter</a>
 * @version $Id$
 */
public class UploadMeter implements TransferListener
{
    /** log for debug output */
    private static final Log log = LogFactory.getLog(UploadMeter.class);

    private int shownSoFar;
    private final int numHashes;
    private final char hashChar;
    private long complete;
    private long total;

    private static final int KB = 1024;

    public UploadMeter()
    {
        this( 20, '.' );
    }

    public UploadMeter(int numHashes, char hashChar)
    {
        this.numHashes = numHashes;
        this.hashChar = hashChar;
    }

    public void transferInitiated( TransferEvent transferEvent )
    {
        System.out.println( "Uploading to " + transferEvent.getResource().getName() + ": " );
    }

    public void transferStarted( TransferEvent transferEvent )
    {
        shownSoFar = 0;
        complete = 0;
        total = transferEvent.getLocalFile().length();
    }

    public void transferProgress( TransferEvent transferEvent, byte[] buffer, int length )
    {
        complete += length;

        if (total > 0)
        {
            int numToShow = (int) ( ( complete * numHashes ) / total );
            for ( int i = shownSoFar + 1; i <= numToShow; i++ )
            {
                System.out.print( hashChar );
            }
            shownSoFar = numToShow;
        }
    }

    public void transferCompleted( TransferEvent transferEvent )
    {
        System.out.println(" (" + total / KB + "K)");
    }

    public void transferError( TransferEvent transferEvent )
    {
        log.error( transferEvent.getException().getMessage() );
    }

    public void debug( String message )
    {
        log.debug( message );
    }
}

