//=-- HourlyGraphPlugin.h - Graphs accesses by the hour ----------------------=
//
//  This class 
//
//=---------------------------------------------------------------------------=
//  This file is copyright (c) 1997-1998 Chris Lattner
//=---------------------------------------------------------------------------=

#include "DataGraph.h"
#include "HourlyGraphPlugin.h"
#include "SerializeEx.h"
#include "Options.h"
#include "Table.h"

INIT_PLUGIN(HourlyGraphPlugin);

HourlyGraphPlugin::HourlyGraphPlugin(int &CE) {
  Flags = FAutoFilter | FIgnoreErrors;
  ResetState();
}

void HourlyGraphPlugin::GetFullName(VarTable &Params, String &fullName, 
                                    int updateFreq) {
  String Filt;
  if (Params["Filter"] != 0) {
    Filt = Params["Filter"]->GetStringValue();
  } else {
    Filt = DefFilter.ToParamStr();
  }

  fullName = String::IntToStr(updateFreq) + Name + "\t" + Filt;
}

void HourlyGraphPlugin::ResetState() { 
  int i;
  for (i = 0; i < 24; i++) 
    HourCount[i] = 0;
}

void HourlyGraphPlugin::ProcessAccess(AccessFormatPlugin &A) {
  HourCount[A.GetDate().GetHour()]++;
}

void HourlyGraphPlugin::LoadState(Serialize &I) {
  unsigned int Version = 0;

  I >> Version;

  // Check version number...
  switch (Version) {
  case 100:                  // Version 1.00
    DeSerializeArray(I, HourCount, 24);
    break;
    
  default:
    cout << "Serialized " << Name << " Page plugin is of a version that cannot "
         << "be deserialized\nwith this version of the plugin.  Reseting state.\n";
    break;
  }
}

void HourlyGraphPlugin::SaveState(Serialize &O) {
  O << GetCurrentVersion();  // Serialize the Version number

  SerializeArray(O, HourCount, 24);
}

void HourlyGraphPlugin::OutputHTML(ostream &O, VarTable &Params) {
  DataGraph Data(Params);

  LinkedList<String> Hours, Count;
  int AccessSum = 0, HourMax = 0, HourMin = 0, 
      CurHour = MSOptions::CurDate.GetHour();
  int i = 0;

  Data.SetRowLabelFormat(2);     // Hour bar labels
  Data.AddColumn(Hours);
  Data.AddColumn(Count);

  Hours.AddToTail("Hour #");
  Count.AddToTail("Hits:");

  for (i = 0; i < 24; i++) {  
    if (CurHour >= i) {          // Only include hours that have happened so far...
      if (HourCount[i] > HourMax) HourMax = HourCount[i];
      if (HourCount[i] < HourMin) HourMin = HourCount[i];
    }

    AccessSum += HourCount[i];
    Count.AddToTail(String::IntToStr(HourCount[i]));
    Hours.AddToTail(String::IntToStr(i+1));
  }

  if (HourMax == 0) HourMax = 1;

  O << "<TABLE width=100% border=0 cellspacing=0 cellpadding=0><TR><TD\n>";
  Data.WriteHTML(O);

  O << "<p>\n</TD><TD VALIGN=TOP>" << endl

    << "Average Accesses per Hour: <b>" << AccessSum / (CurHour+1) << "</b><br>" << endl
    << "Maximum Accesses per Hour: <b>" << HourMax << "</b><br>" << endl
    << "Minimum Accesses per Hour: <b>" << HourMin << "</b><br>" << endl
    << "</TD></TR></TABLE><p><p>" << endl;
}
