/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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.
 */

package org.jboss.installer;


public class ProgressBar {

    private StringBuilder progress;
    private String name;
    private SpinningBar progressSpinner;

    /**
     * initialize progress bar properties.
     */
    public ProgressBar() {
        init();
    }

    public void start(String phaseName, boolean spinningFlag) {
        if (!phaseName.equals(name)) {
            if (progressSpinner.isRunning()) {
                finishUpdateForCleanup();
            }
            System.out.println(phaseName);
            if (spinningFlag) {
                startUpdateForCleanup();
            } else {
                update(0);
            }
        }
        this.name = phaseName;
    }

    public void update(int done) {
        char[] chars = {'|', '/', '-', '\\'};
        String format = "\r%3d%% %s %c";

        int extraChars = (done / 2) - this.progress.length();

        while (extraChars-- > 0) {
            progress.append('#');
        }
        System.out.printf(format, done, progress,
                chars[done % chars.length]);
    }

    public void startUpdateForCleanup(){
        progressSpinner.start();
    }

    public void finishUpdateForCleanup(){
        progressSpinner.finish();
    }

    public void complete() {
        if (!progressSpinner.isRunning()) {
            update(100);
        } else {
            finishUpdateForCleanup();
        }
        System.out.flush();
        System.out.println();
        init();
    }

    private void init() {
        this.progress = new StringBuilder(60);
        name = null;
        progressSpinner = new SpinningBar();
    }
}
