/*                          
 * mBench: The Open Source Micro Benchmark Tool 
 *                                             
 * Distributable under GPL license. 
 * See terms of license at gnu.org.                 
 *
 * Copyright (C) 2005 Sumisho Computer Systems Corp.
 */
package test.jp.co.scs.mbench.stub;

import jp.co.scs.mbench.component.BenchmarkSupport;

/**
 *      The stub for testing BenchmarkManager.
 *      This stub can sleep for specified time.
 * 
 *      @author Tetsuro Ikeda
 */
public class StubBenchmarkManagerComponent2 extends BenchmarkSupport {

    private static int componentCount = 0;
    
    private static int sleepComponentID = 0;
    
    private static int sleepRepeatNumber = 0;

    private int currentRepeatNumber = 0;
    
    private static long sleepTime = 0;
    
    private boolean sleep = false;
    
    public static void setSleepTime(long time) {
        sleepTime = time;
    }

    public static void setSleepComponentID(int id) {
        sleepComponentID = id;
    }
    
    public static void setSleepRepeatNumber(int number) {
        sleepRepeatNumber = number;
    }

    public StubBenchmarkManagerComponent2() {
        super();
        this.sleep = needSleep();
    }
    
    public String[] execute() {
        currentRepeatNumber++;
        if (this.sleep && (currentRepeatNumber >= sleepRepeatNumber)) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException ex) {
                // never come here
            }
            return null;
        } else {
            int minResponseTime = 10;
            int maxResoonseTime = 20;
            int actualResponseTime = minResponseTime +
                (int) ((maxResoonseTime - minResponseTime) * Math.random());
            try {
                Thread.sleep(actualResponseTime);
            } catch (InterruptedException ex) {
                // never come here
            }
            return null;
        }
    }
    
    private synchronized static boolean needSleep() {
        if(componentCount++ == sleepComponentID) {
            return true;
        } else {
            return false;
        }
    }
}
