// ============================================================================
// File:               $File$
//
// Project:            
//
// Purpose:            
//
// Author:             Rammi
//
// Copyright Notice:   (c) 2008  Rammi (rammi@caff.de)
//
// Latest change:      $Date$
//
// History:	       $Log$
//=============================================================================
package de.caff.asteroid.analysis.statistics;

import de.caff.asteroid.analysis.FrameKeyInfo;
import de.caff.asteroid.Property;
import de.caff.i18n.I18n;

import java.util.*;

/**
 *  The answering times.
 *  Only useful for the de.caff statistics format.
 */
public class AnswerTimesStatistics
        extends AbstractBasicDumpFileStatistics
{
  private static class Counter
  {
    private int counter = 1;

    public void advance()
    {
      ++counter;
    }

    public int getCounter()
    {
      return counter;
    }

    /**
     * Returns a string representation of the object.
     *
     * @return a string representation of the object.
     */
    @Override
    public String toString()
    {
      return Integer.toString(counter);
    }
  }
  private SortedMap<Long, Counter> stats = new TreeMap<Long, Counter>();

  /**
   * Analyse the frames.
   *
   * @param infos frame key infos to analyse
   */
  public void analyse(Collection<FrameKeyInfo> infos)
  {
    for (FrameKeyInfo info: infos) {
      if (!info.getButtons().isEmpty()) {
        Long duration = info.getButtons().get(0).getTimestamp() - info.getFrameInfo().getReceiveTime();
        Counter counter = stats.get(duration);
        if (counter == null) {
          counter = new Counter();
          stats.put(duration, counter);
        }
        else {
          counter.advance();
        }
      }
    }
  }

  /**
   * Get a title for this statistics.
   *
   * @return statistics title
   */
  public String getTitle()
  {
    return I18n.getString("titleAnswerTimeStat");
  }

  /**
   * Does this statistic need prepared frames?
   *
   * @return the answer
   */
  public boolean needPreparation()
  {
    return false;
  }

  @Override
  protected String getLeftColumnAlign()
  {
    return VAL_ALIGN_RIGHT;
  }

  /**
   * Get the properties of this object.
   *
   * @return collection of properties
   */
  public Collection<Property> getProperties()
  {
    Collection<Property> props = new ArrayList<Property>(stats.size()+1);
    long average = 0;
    int  frames  = 0;
    for (Long duration: stats.keySet()) {
      Counter counter = stats.get(duration);
      props.add(new Property<Counter>(String.format("%d ms", duration), counter));
      average += duration.longValue() * counter.getCounter();
      frames  += counter.getCounter();
    }
    props.add(new Property<String>(I18n.getString("propAnswerTimeAverage"), String.format("%f ms", average/(double)frames)));
    return props;
  }
}
