// -*- C++ -*-
//
// Package:    NoiseEvents
// Class:      NoiseEvents
// 
/**\class NoiseEvents NoiseEvents.cc Visualisation/NoiseEvents/src/NoiseEvents.cc

 Description: <one line class summary>

 Implementation:
     <Notes on implementation>
*/
//
// Original Author:  CMS TAC monitor user
//         Created:  Mon Nov 24 13:40:02 CET 2008
// $Id$
//
//


// system include files
#include <memory>

// user include files
#include "CommonTools/FillTmap/interface/FillTmap.h"
#include "CommonTools/TrackerMap/interface/TrackerMap.h"
#include "FWCore/Framework/interface/EDAnalyzer.h"

#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/Framework/interface/ESHandle.h"

#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDFilter.h"

#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"

#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/TrackReco/interface/TrackFwd.h"
#include "DataFormats/SiStripCluster/interface/SiStripClusterCollection.h"
#include "DataFormats/Common/interface/DetSetVectorNew.h"
#include "DataFormats/SiStripDigi/interface/SiStripDigi.h"
#include "DataFormats/Common/interface/DetSetVector.h"
#include <fstream>

using namespace std;
using namespace edm;
//
// class declaration
//

class FillTmap : public edm::EDFilter {
   public:
      explicit FillTmap(const edm::ParameterSet&);
      ~FillTmap();

   private:
      virtual void beginJob(const edm::EventSetup&) ;
      virtual bool filter(edm::Event&, const edm::EventSetup&);
      virtual void endJob() ;
      
      // ----------member data ---------------------------
      unsigned int          SRun;
      unsigned int          SEvent;
      int                   NEvents;
      unsigned int          PEvent,POrbit,PBX;
      int                    DBX;
      std::ofstream * output;
      TrackerMap* tmap;
//      std::vector<InputTag> SiStripClusterProducers;

};

//
// constants, enums and typedefs
//

//
// static data member definitions
//

//
// constructors and destructor
//
FillTmap::FillTmap(const edm::ParameterSet& iConfig)
{
   //now do what ever initialization is needed
   //SiStripClusterProducers = iConfig.getParameter<std::vector<InputTag> >("SiStripClusterProducers");
   NEvents=0;
   tmap = new TrackerMap("rechit distribution");

}


FillTmap::~FillTmap()
{
 
   // do anything here that needs to be done at desctruction time
   // (e.g. close files, deallocate resources etc.)
   tmap->save(true,0,0,"tmap.png");
   delete tmap;

}


//
// member functions
//

// ------------ method called on each new Event  ------------
bool
FillTmap::filter(edm::Event& iEvent, const edm::EventSetup& iSetup)
{
   using namespace edm;
if(NEvents == 0){
           SRun   = iEvent.id().run();
           SEvent = iEvent.id().event();
           PEvent = iEvent.id().event();
           POrbit = iEvent.orbitNumber ();
           PBX = iEvent.bunchCrossing ();
           output = new std::ofstream("ennupla.txt",std::ios::out);
         }
     NEvents++;
DBX=-1;if(iEvent.id().event() == (PEvent+1)){DBX = (iEvent.bunchCrossing ()-PBX)+(iEvent.orbitNumber ()-POrbit)*3564;}
        PEvent = iEvent.id().event(); POrbit = iEvent.orbitNumber (); PBX = iEvent.bunchCrossing ();
//        std::cout << iEvent.id().run() << " " << iEvent.id().event() << " " << iEvent.luminosityBlock() << " " << iEvent.orbitNumber () << " " << iEvent.bunchCrossing () << " " << DBX << endl;
           std::string srcTracks = "ctfWithMaterialTracksP5";
           bool notracks=true;
           int nt=0;
          edm::Handle<reco::TrackCollection>  trackCollection;
          try
         {
          iEvent.getByLabel(srcTracks,trackCollection);
          notracks=false;
          }
  catch (...)
    {
      cout << "no tracks type"<<"ctfWithMaterialTracksP5"<< " in event" << endl;
    }
          if(!notracks) { 
           nt = trackCollection->size();
           for (reco::TrackCollection::const_iterator track = trackCollection->begin (); track != trackCollection->end (); track++)
              { 
              for (trackingRecHit_iterator it = track->recHitsBegin ();  it != track->recHitsEnd (); it++)
                    {
                    if (!((*it)->geographicalId ().null ())) {
                        DetId detIdObject  = (*it)->geographicalId ();
                        unsigned int id = detIdObject.rawId();
                        if((id%10)!=0)tmap->fill(id ,1.); else {tmap->fill(id+1,1.);tmap->fill(id+2,1.);}
                     }
                     }
               }
           }
        int ndigmodules=0;
  //      std::string digiProducer="siStripDigis";
   //     std::string digiLabel="ZeroSuppressed";
    //    edm::Handle<edm::DetSetVector<SiStripDigi> > digiCollection;
     //   iEvent.getByLabel(digiProducer,digiLabel, digiCollection);
      //  const edm::DetSetVector<SiStripDigi>&  sinput = *digiCollection.product();
       // ndigmodules=sinput.size();
        int nfirmodules=0;
        std::string clusterProducer="siStripClusters";
    //    for(unsigned int i=0;i<SiStripClusterProducers.size();i++){
           edm::Handle<edmNew::DetSetVector<SiStripCluster> > h_Sst_Hits;
           iEvent.getByLabel(clusterProducer, h_Sst_Hits);
           const edmNew::DetSetVector<SiStripCluster>&  Sst_Hits = *h_Sst_Hits.product();
           nfirmodules=Sst_Hits.size();
//}
        //*output << iEvent.id().run() << " " << iEvent.id().event() << " " << iEvent.luminosityBlock() << " " << iEvent.orbitNumber () << " " << iEvent.bunchCrossing () << " " << DBX << " " << nt << " " << nfirmodules << " " << ndigmodules << endl;
        *output << iEvent.id().run() << " " << iEvent.id().event() << " " << iEvent.luminosityBlock() << " " << iEvent.orbitNumber () << " " << iEvent.bunchCrossing () << " " << DBX << " " << nt << " " << nfirmodules << endl;

#ifdef THIS_IS_AN_EVENT_EXAMPLE
   Handle<ExampleData> pIn;
   iEvent.getByLabel("example",pIn);
#endif

#ifdef THIS_IS_AN_EVENTSETUP_EXAMPLE
   ESHandle<SetupData> pSetup;
   iSetup.get<SetupRecord>().get(pSetup);
#endif
   if(nt>1 || nfirmodules > 40)return true; 
       else return false;
}

// ------------ method called once each job just before starting event loop  ------------
void 
FillTmap::beginJob(const edm::EventSetup&)
{
}

// ------------ method called once each job just after ending the event loop  ------------
void 
FillTmap::endJob() {
}

//define this as a plug-in
DEFINE_FWK_MODULE(FillTmap);
