/*
 * SaveEventsAction.cpp
 *
 *  Created on: 16-mag-2009
 *      Author: Nicola Mori
 */

/*! @file SaveEventsAction.cpp The SaveEventsAction class implementation file */

#include "SaveEventsAction.h"

SaveEventsAction::SaveEventsAction(const char *actionName, TString outFileName, TString outOptions,
    Long64_t maxFileSize) :
  CollectionAction(actionName), _outTreeFile(NULL), _events(NULL), _outOptions(outOptions), _outFileName(outFileName),
      _maxFileSize(maxFileSize) {

}

void SaveEventsAction::Setup(PamLevel2 *events) {

  // Open output file
  /* Due to the combined weirdness of PamLevel2 and ROOT, this pointer must NOT
   * be explicitly deleted, nor the file closed. This would generate a double
   * deletion in the destructors chain. This mechanism is not completely clear
   * but it indeed happens...
   */

  _outTreeFile = new TFile(_outFileName, "RECREATE");

  if (_outTreeFile->IsZombie()) {
    cout << "Output file could not be created\n";
    _outTreeFile->Delete();
    //TODO Gestire con un'eccezione
    return;
  }

  _events = events;
  if (_outOptions.Length() > 0)
    _events->SetWhichTrees(_outOptions);
  _events->CreateCloneTrees(_outTreeFile);

  // Set the output file size
  TTree * currTree = NULL;
  if ((currTree = _events->GetCloneTree("Run")))
    currTree->SetMaxTreeSize(_maxFileSize);
  currTree = NULL;
  if ((currTree = _events->GetCloneTree("SelectionList")))
    currTree->SetMaxTreeSize(_maxFileSize);
  currTree = NULL;
  if ((currTree = _events->GetCloneTree("Tracker")))
    currTree->SetMaxTreeSize(_maxFileSize);
  currTree = NULL;
  if ((currTree = _events->GetCloneTree("Calorimeter")))
    currTree->SetMaxTreeSize(_maxFileSize);
  currTree = NULL;
  if ((currTree = _events->GetCloneTree("ToF")))
    currTree->SetMaxTreeSize(_maxFileSize);
  currTree = NULL;
  if ((currTree = _events->GetCloneTree("Trigger")))
    currTree->SetMaxTreeSize(_maxFileSize);
  currTree = NULL;
  if ((currTree = _events->GetCloneTree("S4")))
    currTree->SetMaxTreeSize(_maxFileSize);
  currTree = NULL;
  if ((currTree = _events->GetCloneTree("NeutronD")))
    currTree->SetMaxTreeSize(_maxFileSize);
  currTree = NULL;
  if ((currTree = _events->GetCloneTree("Anticounter")))
    currTree->SetMaxTreeSize(_maxFileSize);
  currTree = NULL;
  if ((currTree = _events->GetCloneTree("OrbitalInfo")))
    currTree->SetMaxTreeSize(_maxFileSize);
  currTree = NULL;
  if ((currTree = _events->GetCloneTree("h20")))
    currTree->SetMaxTreeSize(_maxFileSize);

}

void SaveEventsAction::OnGood(PamLevel2 *event) {
  // Fill the tree
  event->FillCloneTrees();
}

void SaveEventsAction::Finalize() {
  _outTreeFile->cd();
  _events->WriteCloneTrees();

}
