/*
 * JORAM: Java(TM) Open Reliable Asynchronous Messaging
 * Copyright (C) 2020 ScalAgent Distributed Technologies
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA.
 *
 * Initial developer(s): ScalAgent Distributed Technologies
 * Contributor(s): 
 */
package fr.dyade.aaa.common;

import java.lang.management.ManagementFactory;
import java.util.Timer;
import java.util.TimerTask;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * This class computes the average CPU use by a thread during last minute.
 */
public final class AverageCPUTask extends TimerTask {
  /** logger */
  private Logger logger;

  long[] cpuTime;
  int idx;
  int nb;
  
  /** the thread ID of the monitored thread */
  private long id;
  /** the thread name of the monitored thread */
  private String name;
  
  private int average;
  
  public int getAverage() {
    return average;
  }
  
  /**
   * Creates a task that periodically computes the thread load.
   * 
   * @param id thread ID of the monitored thread
   * @param nb number of refresh per minute
   */
  public AverageCPUTask(long id, int nb) {
    this.id = id;
    this.name = ManagementFactory.getThreadMXBean().getThreadInfo(id).getThreadName();
    logger =  Debug.getLogger(AverageCPUTask.class.getName() + '.' + name);
    this.nb = nb;
    this.cpuTime = new long[nb];
    this.idx = 0;
  }
  
  /**
   * @see java.util.TimerTask#run()
   */
  @Override
  public void run() {
    try {
      // Collects the current CPU time.
      cpuTime[idx%nb] = ManagementFactory.getThreadMXBean().getThreadCpuTime(id);
      // Computes the CPU time used during last minute
      average = (int) ((cpuTime[idx%nb] - cpuTime[(idx+1)%nb]) / ((60L *1000000000L) / 100L));
      logger.log(BasicLevel.DEBUG,
                 "AverageCPUTask: " + name + " CPU Time: " + cpuTime[idx%nb] + "ns -> " + average);
      idx += 1;
    } catch (Throwable t) {
      logger.log(BasicLevel.WARN, "AverageCPUTask.run", t);
    }
  }
  
  /**
   * Starts the resulting task.
   * 
   * @param timer Timer to use to schedule the resulting task.
   */
  public void start(Timer timer) {
    long period = 60000L / nb;
    timer.scheduleAtFixedRate(this, period, period);
  }
}
