#include <CLHEP/Random/RandFlat.h>

#include <G4ThreeVector.hh>

#include <RAT/SimpleDAQProc.hh>
#include <RAT/Log.hh>
#include <RAT/DS/Entry.hh>
#include <RAT/DS/MCHit.hh>
#include <RAT/DS/MCPE.hh>
#include <RAT/DU/Utility.hh>
#include <RAT/DU/PMTInfo.hh>

#include <vector>

using namespace std;

namespace RAT {


Processor::Result SimpleDAQProc::DSEvent(DS::Run& run, DS::Entry& ds)
{
  // This simple simulation assumes only tubes hit by a photon register
  // a hit, and that every MC event corresponds to one triggered event
  // The time of the PMT hit is that of the first photon.

  // -- First check that the MC branch does exist. In case of real data it won't exist
  // Of course, I have no idea why people would run this processor on real data, but
  // better safe than sorry
  if (!run.GetMCFlag()) {
    warn << "SimpleDAQProc::DSEvent : There is no MC branch for this Run. Most likely this is real data. Aborting..." << newline;
    warn << "SimpleDAQProc::DSEvent : Check the options in your macro, and your input file." << newline;
    return Processor::ABORT;
  }

  DS::MC& mc = ds.GetMC();
  DS::EV ev;
  DS::MCEV mcev;

  float totalQ = 0.0;

  for( size_t imcpmt=0; imcpmt < mc.GetMCPMTCount(); imcpmt++) {
    DS::MCPMT& mcpmt = mc.GetMCPMT(imcpmt);

    if (mcpmt.GetMCPECount() > 0) {
      // Need at least one photoelectron to trigger
      DS::MCHit newHit;
      newHit.SetID(mcpmt.GetID());
      // Set flags to 0, and generate random cell ID
      UShort_t cell = UShort_t(16*CLHEP::RandFlat::shoot());
      if(cell>15)cell=15;
      newHit.SetCellID(cell);

      // Create one sample, hit time is determined by first hit,
      // "infinite" charge integration time
      // WARNING: gets multiphotoelectron effect right, but not walk correction
      newHit.SetTime(mcpmt.GetMCPE(0).GetFrontEndTime());

      float charge = 0.0;
      for (size_t i=0; i < mcpmt.GetMCPECount(); i++)
        charge += mcpmt.GetMCPE(i).GetCharge();
      newHit.SetQHS(charge);

      mcev.GetMCHits().AddPMT( newHit, DU::Utility::Get()->GetPMTInfo().GetType( newHit.GetID() ) );
      totalQ += charge;
    } // if at least one photoelectron
  } // loop over MCPMT

  ev.SetTotalCharge(totalQ);
  ds.AddEV( ev );
  ds.AddMCEV( mcev );

  return Processor::OK;
}


} // namespace RAT