#ifndef RunControl_HH
#define RunControl_HH

#include <sys/types.h>
#include <unistd.h>
#include <time.h>

#include <string>

#include "DaqRunStart.hh"
#include "IlcRunStart.hh"
#include "RcdHeader.hh"


class RunControl {

public:
  enum {
    shmKey=0x76543212
  };

  enum Flag {
    shutDown,
    sequenceEnd,
    runEnd,
    configurationEnd,
    acquisitionEnd,
    spillEnd,
    transferStart,
    daqContinue,
    endOfFlagEnum
  };

  RunControl() : _pid(0) {
    reset();
  }

  void runRegister() {
    _pid=getpid();
  }
 
  void runInterrupt(int s) const {
    if(_pid!=0) kill(_pid,s);
  }

  Flag flag() const {
    return _flag;
  }

  void flag(Flag f) {
    _flag=f;
  }

  static std::string flagName(Flag f) {
    if(f<endOfFlagEnum) return _flagName[f];
    return "unknown";
  }

  std::string flagName() const {
    return flagName(_flag);
  }

  unsigned numberOfRuns() const {
    return _numberOfRuns;
  }

  void numberOfRuns(unsigned n) {
    _numberOfRuns=n;
  }

#ifndef DAQ_ILC_TIMING
  DaqRunStart runStart() const {
    return _runStart;
  }

  void runStart(DaqRunStart r) {
    _runStart=r;
  }
#else
  IlcRunStart runStart() const {
    return _runStart;
  }

  void runStart(IlcRunStart r) {
    _runStart=r;
  }
#endif

  void reset() {
    _flag=daqContinue;
    _numberOfRuns=1;
    _runStart.reset();

#ifndef DAQ_ILC_TIMING
    DaqRunType runType;
    runType.type(DaqRunType::slowMonitor);
    runType.printLevel(9);
#else
    IlcRunType runType;
    runType.type(IlcRunType::slwMonitor);
    runType.printLevel(12);
#endif
    runType.version(0);
    runType.switches(0);

    _runStart.runType(runType);
  }

  std::ostream& print(std::ostream& o, std::string s="") const {
    o << s << "RunControl::print()" << std::endl;

    o << s << " Runner pid = " << _pid << std::endl;
    o << s << " Run control flag = " << _flag 
      << " = " << flagName() << std::endl;
    o << s << " Number of runs  = " << _numberOfRuns << std::endl;
    
    _runStart.print(o,s+" ");
    return o;
  }

private:
  static const std::string _flagName[endOfFlagEnum];

  pid_t _pid;
  Flag _flag;
  unsigned _numberOfRuns;
#ifndef DAQ_ILC_TIMING
  DaqRunStart _runStart;
#else
  IlcRunStart _runStart;
#endif
};

const std::string RunControl::_flagName[]={
  "shutDown",
  "sequenceEnd",
  "runEnd",
  "configurationEnd",
  "acquisitionEnd",
  "spillEnd",
  "spillStart", // "transferStart"???
  "daqContinue"
};

#endif
