#ifndef DaqSink_HH
#define DaqSink_HH

#include <vector>
#include <fstream>
#include <iostream>

// dual/inc/rcd
#include "RcdUserRW.hh"
#include "SlwWriter.hh"
#include "SubModifier.hh"
#include "DaqStateData.hh"
#include "DaqCounter.hh"


class DaqSink : public RcdUserRW {

public:
  DaqSink() {
  }

  virtual ~DaqSink() {
  }

  bool record(RcdRecord &r) {
    SubModifier accessor(r);

    std::vector<DaqStateData*> v(accessor.access<DaqStateData>());
    assert(v.size()==1);

    //_writer.record(r);
    //if(_writer.numberOfBytes()>10000000) v[0]->target(2,1);

    // Check record type
    switch (r.recordType()) {

    case RcdHeader::startUp: {
      v[0]->finalState(1);
      break;
    }

    case RcdHeader::runStart: {
      v[0]->finalState(2);
      break;
    }
      
    case RcdHeader::slowControl: {
      v[0]->finalState(3);
      break;
    }
      
    case RcdHeader::configurationStart: {
      v[0]->finalState(4);
      break;
    }

    case RcdHeader::preEvent: {
      v[0]->finalState(5);
      break;
    }

    case RcdHeader::slowReadout: {
      v[0]->finalState(4);
      break;
    }
 
    case RcdHeader::event: {
      v[0]->finalState(4);
      break;
    }

    case RcdHeader::configurationEnd: {
      v[0]->finalState(3);
      break;
    }

    case RcdHeader::runEnd: {
      v[0]->finalState(1);
      break;
    }

    case RcdHeader::shutdown: {
      v[0]->finalState(0);
      break;
    }

    default: {
      assert(false);
      break;
    }
    };

    v[0]->print(std::cout);

    _counter.printLevel(9);
    _counter.record(r);
    if(_counter.endSpill()        ) v[0]->target(3,4);
    if(_counter.endConfiguration()) v[0]->target(3,3);
    //if(_counter.endRun()          ) v[0]->target(3,1);

    v[0]->print(std::cout);

    return true;
  }
  
private:
  SlwWriter _writer;
  DaqCounter _counter;
};

#endif
