#ifndef MpsLaserReadout_HH
#define MpsLaserReadout_HH

#include <iostream>
#include <fstream>

#include "RcdUserRW.hh"

#include "SubRecordType.hh"
#include "SubInserter.hh"
#include "SubAccessor.hh"

// TEMP!
#include "MpsUsbDevice.hh"


class MpsLaserReadout : public RcdUserRW {

public:
  MpsLaserReadout() {
  }

  virtual ~MpsLaserReadout() {
  }

  virtual bool record(RcdRecord &r) {
    if(doPrint(r.recordType())) {
      std::cout << "MpsLaserReadout::record()" << std::endl;
      r.RcdHeader::print(std::cout," ") << std::endl;
    }

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

      // Run start
    case RcdHeader::runStart: {

      // Reset whole system and then readback run data
      //reset????
      readRunData(r);

      break;
    }
 
      // Configuration start is used to set up system
    case RcdHeader::configurationStart: {
      SubAccessor accessor(r);

      std::vector<const MpsLaserConfigurationData*>
        v(accessor.access<MpsLaserConfigurationData>());
      
      if(doPrint(r.recordType(),1)) {
	std::cout << " MpsLaserReadout::record()  configurationStart"
		  << ", number of MpsLaserConfigurationData objects found = "
		  << v.size() << std::endl << std::endl;
      }

      assert(v.size()<2);

      for(unsigned i(0);i<v.size();i++) {
	if(doPrint(r.recordType(),2)) {
	  std::cout << " MpsLaserReadout::record()  configurationStart"
		    << ", writing MpsLaserConfigurationData object "
		    << i << std::endl;
	  v[i]->print(std::cout,"  ") << std::endl;
	}

	// Write data TEMP!!!
	_laserConfigurationData=*(v[i]);
      }

      // Now read back the (non-destructive read) configuration data
      readConfigurationData(r);

      // TEMP!!!
      MpsUsbDevice::coordinates(_laserConfigurationData.stageX(),
				_laserConfigurationData.stageY());

      break;
    }
      
    case RcdHeader::bunchTrain: {

      // Read bunch train data

      break;
    }

    case RcdHeader::configurationEnd: {
      readConfigurationData(r);
      break;
    }
 
      // Run end
    case RcdHeader::runEnd: {

      // Read back run data
      readRunData(r);

      break;
    }

    default: {
      break;
    }
    };
    
    return true;
  }

private:
  bool readRunData(RcdRecord &r) {
    //SubInserter inserter(r);
    return true;
  }

  bool readConfigurationData(RcdRecord &r) {
    SubInserter inserter(r);

    MpsLaserConfigurationData
      *m(inserter.insert<MpsLaserConfigurationData>());

    // Read back data TEMP!!!!
    *m=_laserConfigurationData;

    if(doPrint(r.recordType(),2)) {
      std::cout << " MpsLaserReadout::readConfigurationData()"
		<< ", read MpsLaserConfigurationData object " << std::endl;
      m->print(std::cout," ") << std::endl;
    }

    return true;
  }


  MpsLaserConfigurationData _laserConfigurationData;
};

#endif
