#ifndef __JTRIGGER__JDOMTOPMTMASKMAP__
#define __JTRIGGER__JDOMTOPMTMASKMAP__

#include <istream>
#include <ostream>
#include <map>

#include "JTrigger/JPMTMask.hh"
#include "JDetector/JModuleIdentifier.hh"
#include "JLang/JException.hh"
#include "JIO/JSerialisable.hh"

/**
 * \author rbruijn
 */

namespace JTRIGGER {}
namespace JPP { using namespace JTRIGGER; }

namespace JTRIGGER {

  using JDETECTOR::JModuleIdentifier;
  using JLANG::JException;
  using JIO::JSerialisable;
  using JIO::JReader;
  using JIO::JWriter;
  using JTRIGGER::JPMTMask;

  class JDOMToPMTMaskMap :
    public std::map<JModuleIdentifier, JPMTMask>,
    public JIO::JSerialisable
  {
  public:
    
    JDOMToPMTMaskMap():
      std::map<JModuleIdentifier, JPMTMask>(),
      JSerialisable()
    {}
    
    const JPMTMask& getPMTMask(const JModuleIdentifier& id)
    {
      return at(id);
    }
    
    
    friend inline std::istream& operator>>(std::istream& in, JDOMToPMTMaskMap& masks)
    {
      masks.clear();
      
      unsigned int n;
      
      if(in >> n) {
      
	JModuleIdentifier id;
	JPMTMask mask;
	
	for(; n !=0 && in; --n) {
	  
	  in >> id >>mask;
	  
	  if(!(masks.insert(std::make_pair(id,mask))).second) {
	      throw JException("Key already exists in map.");
	    }
	    }
      }
	
	return in;
      }
    
    friend inline std::ostream& operator<<(std::ostream& out, const JDOMToPMTMaskMap& masks)
    {
      using namespace std;
      
      out << masks.size();
      out << endl;
      
      for(std::map<JModuleIdentifier, JPMTMask>::const_iterator dommask = masks.begin(); 
	  dommask!=masks.end();++dommask)
	{
	  out << dommask->first << ' ' << dommask->second << endl;
	  
	}
      return out;
    }
    
    virtual JReader& read(JReader & in) override 
    {
      clear();
      
      unsigned int n;
      
      if(in >> n) {
	
    	JModuleIdentifier id;
    	JPMTMask mask;
	
    	for(; n !=0 && in; --n) {
	  
    	  in >> id >>mask;
	  
    	  if(!(insert(std::make_pair(id,mask))).second) {
    	    throw JException("Key already exists in map.");
    	  }
    	}
      }
      
      return in;
    }
    
    
    virtual JWriter& write(JWriter& out) const override 
    {
      using namespace std;
      
      unsigned int n = size();

      out << n;
      
      for(std::map<JModuleIdentifier, JPMTMask>::const_iterator dommask= this->begin(); 
    	  dommask!=this->end(); ++dommask )
    	{
    	  out << dommask->first 
    	      << dommask->second;
	  
    	}
      return out;
    } 


    // ClassDef(JDOMToPMTMaskMap,1);
    };


  }



#endif