/*
 * MaskedCollection.cpp
 *
 *  Created on: 19-apr-2011
 *      Author: Nicola Mori
 */

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

#include "MaskedCollection.h"

void MaskedCollection::AddCut(PamCut *cut) {
  VerboseCollection::AddCut(cut);
  _mask.push_back(false);
}

void MaskedCollection::AddInverseCut(PamCut *cut) {
  VerboseCollection::AddCut(cut);
  _mask.push_back(true);
}

// This is basically SmartCollection::ApplyCut with added mask support
int MaskedCollection::ApplyCut(PamLevel2 *event) {

  _nEv++;

  // Execute the actions placed before the cuts
  unsigned int iBeforeCuts = 0;
  //cout << GetName() << endl;
  if (_actions.size() > 0) {
    while (_actionsPositions[iBeforeCuts] == -1) {
      _actions[iBeforeCuts]->OnGood(event);
      iBeforeCuts++;
      if (iBeforeCuts == _actions.size())
        break;
    }
  }

  // Apply the cuts
  if (_cuts.size() == 0) {
    _nGood++;
    OnGood(event);
    return CUTOK;
  }

  unsigned int firstFailed = _cuts.size();
  unsigned int iAction = iBeforeCuts;
  bool cutResult;
  for (unsigned int iCut = 0; iCut < _cuts.size(); iCut++) {
    cutResult = (_cuts[iCut]->ApplyCut(event) == CUTOK);
    if (_mask[iCut])
      cutResult = !cutResult;
    if (!cutResult && firstFailed == _cuts.size()) {
      firstFailed = iCut;
      // Apply the bad actions at the end of the bunch
      if (iAction < _actions.size()) {
        unsigned int lastPosition = _actionsPositions[iAction];
        for (; iAction < _actions.size(); iAction++) {
          if (_actionsPositions[iAction] > (int) lastPosition) // Don't do actions at the end of successive bunches
            break;
          _actions[iAction]->OnBad(event, (int) firstFailed);

        }
      }
      break;
    }
    else if (iAction < _actions.size()) {
      // Do the good actions if we are at the end of the bunch
      while (_actionsPositions[iAction] == (int) iCut) {
        _actions[iAction]->OnGood(event);
        iAction++;
        if (iAction == _actions.size())
          break;
      }
    }
  }

  if (firstFailed == _cuts.size()) {
    _nGood++;
    OnGood(event);
    return CUTOK;
  }
  else {
    OnBad(event, firstFailed);
    return firstFailed;
  }
}
