/* ======================================================================== *\
!
! *
! * This file is part of MARS, the MAGIC Analysis and Reconstruction
! * Software. It is distributed to you in the hope that it can be a useful
! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
! * It is distributed WITHOUT ANY WARRANTY.
! *
! * Permission to use, copy, modify and distribute this software and its
! * documentation for any purpose is hereby granted without fee,
! * provided that the above copyright notice appear in all copies and
! * that both that copyright notice and this permission notice appear
! * in supporting documentation. It is provided "as is" without express
! * or implied warranty.
! *
!
!
!   Author(s): Markus Gaug, 09/2004 <mailto:markus@ifae.es>
!         
!   Copyright: MAGIC Software Development, 2000-2004
!
!
\* ======================================================================== */
//////////////////////////////////////////////////////////////////////////////
//
//  MCalibColorSteer
//
//  Steers the occurrance of different calibration colours in one calibration 
//  run. 
// 
//  Input Containers:
//   MRawEvtHeader
//   MParList
//   MCalibrationIntensityChargeCam
//   MCalibrationIntensityRelTimeCam
//
//  Output Containers:
//   MCalibrationIntensityChargeCam
//   MCalibrationIntensityRelTimeCam
//
//////////////////////////////////////////////////////////////////////////////
#include "MCalibColorSteer.h"

#include "MLog.h"
#include "MLogManip.h"

#include "MParList.h"

#include "MHCalibrationCam.h"

#include "MCalibrationIntensityChargeCam.h"
#include "MCalibrationIntensityQECam.h"
#include "MCalibrationIntensityRelTimeCam.h"

#include "MRawEvtHeader.h"

#include "MGeomCam.h"

ClassImp(MCalibColorSteer);

using namespace std;

// --------------------------------------------------------------------------
//
//  Default constructor. 
//
MCalibColorSteer::MCalibColorSteer(const char *name, const char *title)
    : fHeader(NULL), fGeom(NULL), fParList(NULL), 
      fIntensCharge(NULL), fIntensRelTime(NULL), 
      fPattern(0)
{

  fName  = name  ? name  : "MCalibColorSteer";
  fTitle = title ? title : "Task to steer the processing of different colours in the calibration events";

}

// -----------------------------------------------------------------------------------
//
// The following container are searched for and execution aborted if not in MParList:
//  - MRawEvtHeader
//  - MTaskList
//
Int_t MCalibColorSteer::PreProcess(MParList *pList)
{

  fHeader = (MRawEvtHeader*)pList->FindObject("MRawEvtHeader");
  if (!fHeader)
    {
      *fLog << err << "MRawEvtHeader not found... abort." << endl;
      return kFALSE;
    }

  fGeom = (MGeomCam*)pList->FindObject("MGeomCam");
  if (!fGeom)
    {
      *fLog << err << "MGeomCam not found... abort." << endl;
      return kFALSE;
    }

  fParList = pList;
  if (!fParList)
    {
      *fLog << err << "MParList not found... abort." << endl;
      return kFALSE;
    }

  // 
  // Look for the MFillH name "FillChargeCam". In case yes, initialize the 
  // corresponding IntensityCam
  //
  if (pList->FindObject(AddSerialNumber("FillChargeCam")))
  {
    fIntensCharge = (MCalibrationIntensityChargeCam*)pList->FindCreateObj("MCalibrationIntensityChargeCam");
    fIntensQE     = (MCalibrationIntensityQECam*)    pList->FindCreateObj("MCalibrationIntensityQECam");

    if (!fIntensCharge)
      {
        *fLog << err << "Could not find nor create MCalibrationIntensityChargeCam abort... " << endl;
        return kFALSE;
      }
    
    if (fIntensQE)
      {
        *fLog << err << "Could not find nor create MCalibrationIntensityQECam abort... " << endl;
        return kFALSE;
      }
  }
      
  // 
  // Look for the MFillH name "FillRelTimeCam". In case yes, initialize the 
  // corresponding IntensityCam
  //
  if (pList->FindObject(AddSerialNumber("FillRelTimeCam")))
  {
    fIntensRelTime = (MCalibrationIntensityRelTimeCam*)pList->FindCreateObj("MCalibrationIntensityRelTimeCam");
    if (!fIntensRelTime)
      {
        *fLog << err << "Could not find nor create MCalibrationIntensityRelTimeCam abort... " << endl;
        return kFALSE;
      }
  }
      
  return kTRUE;
}

// --------------------------------------------------------------------------
//
// Sets the pattern to MRawEvtHeader from outside, if fIsValid is set.
//
Int_t MCalibColorSteer::Process()
{

  const UInt_t pattern = fHeader->GetCalibrationPattern();

  if (pattern == fPattern)
    return kTRUE;

  if (fPattern == 0)
    {
      fPattern = pattern;
      //      ReInitialize();
      return kTRUE;
    }

  fPattern = pattern;
  
  //
  // Possible calibration histogram classes...
  //
  *fLog << inf << GetDescriptor() << " : Finalize calibration histograms..." << flush;
  if (Finalize("MHCalibrationChargeCam"))   *fLog << "MHCalibrationChargeCam";
  if (Finalize("MHCalibrationRelTimeCam"))  *fLog << "MHCalibrationRelTimeCam";  
  if (Finalize("MHCalibrationTestCam"))     *fLog << "MHCalibrationChargeCam";  
  if (Finalize("MHCalibrationTestTimeCam")) *fLog << "MHCalibrationChargeCam";  

  ReInitialize();

  return kTRUE;
}

Bool_t MCalibColorSteer::Finalize(const char* name)
{

  MHCalibrationCam *hist = (MHCalibrationCam*)fParList->FindObject(name);
  if (hist)
    {
      hist->Finalize();
      hist->ResetHists();
      return kTRUE;
    }

  return kFALSE;
  
}

Bool_t MCalibColorSteer::ReInitialize()
{
  if (fIntensCharge)
    {
      fIntensCharge->AddToList(Form("MCalibrationChargeCam%s",GetNamePattern()),*fGeom);
      *fLog << inf << "New MHCalibrationChargeCam with " << GetNamePattern() << endl;
    }
  else
    *fLog << warn << GetDescriptor() 
          << ": No MCalibrationIntensityChargeCam loaded, but MHCalibrationChargeCam found " 
          << endl;
  if (fIntensQE)
    {
      fIntensQE->AddToList(Form("MCalibrationQECam%s",GetNamePattern()),*fGeom);
      *fLog << inf << "New MHCalibrationQECam with " << GetNamePattern() << endl;
    }
  else
    *fLog << warn << GetDescriptor() 
          << ": No MCalibrationIntensityQECam loaded, but MHCalibrationChargeCam found " 
          << endl;


  if (fIntensRelTime)
    {
      fIntensRelTime->AddToList(Form("MCalibrationRelTimeCam%s",GetNamePattern()),*fGeom);
      *fLog << inf << "New MHCalibrationRelTimeCam with " << GetNamePattern() << endl;
    }
  else
    *fLog << warn << GetDescriptor() 
          << ": No MCalibrationIntensityRelTimeCam loaded, but MHCalibrationRelTimeCam found " 
          << endl;

  return kTRUE;

}

const char* MCalibColorSteer::GetNamePattern()
{

  Float_t number[MCalibrationCam::gkNumPulserColors];
  memset(number,0,MCalibrationCam::gkNumPulserColors*sizeof(Float_t));

  enum ColorCode_t 
    {
      k5LedGreen   = BIT(0 ),
      k2LedGreen   = BIT(1 ),
      k5LedBlue2   = BIT(2 ),      
      k1LedUV      = BIT(3 ),
      k2LedUV      = BIT(4 ),
      k5LedBlue3   = BIT(5 ),
      k5LedBlue4   = BIT(6 ),
      k2LedBlue    = BIT(7 ),
      k01LedBlue   = BIT(8 ),
      k1LedBlue    = BIT(10),
      k5LedUV1     = BIT(11),
      k5LedUV2     = BIT(12),
      k5LedBlue1   = BIT(13),
      k1LedGreen   = BIT(14),
      k01LedGreen  = BIT(15),
      kCT1Pulser   = BIT(16)
    };

  if (fPattern & k5LedGreen)
    number[MCalibrationCam::kGREEN] += 5;
  if (fPattern & k2LedGreen)
    number[MCalibrationCam::kGREEN] += 2;
  if (fPattern & k5LedBlue2)
    number[MCalibrationCam::kBLUE]  += 2;
  if (fPattern & k1LedUV)           
    number[MCalibrationCam::kUV]    += 1;
  if (fPattern & k2LedUV)           
    number[MCalibrationCam::kUV]    += 2;
  if (fPattern & k5LedBlue3)        
    number[MCalibrationCam::kBLUE]  += 5;
  if (fPattern & k5LedBlue4)        
    number[MCalibrationCam::kBLUE]  += 5;
  if (fPattern & k2LedBlue)         
    number[MCalibrationCam::kBLUE]  += 2;
  if (fPattern & k01LedBlue)        
    number[MCalibrationCam::kBLUE]  += 0.5;
  if (fPattern & k1LedBlue)         
    number[MCalibrationCam::kBLUE]  += 1;
  if (fPattern & k5LedUV1)          
    number[MCalibrationCam::kUV]    += 5;
  if (fPattern & k5LedUV2)        
    number[MCalibrationCam::kUV]    += 5;
  if (fPattern & k5LedBlue1)        
    number[MCalibrationCam::kBLUE]  += 5;
  if (fPattern & k1LedGreen)
    number[MCalibrationCam::kGREEN] += 1;
  if (fPattern & k01LedGreen)
    number[MCalibrationCam::kGREEN] += 0.5;
  if (fPattern & kCT1Pulser)
    number[MCalibrationCam::kCT1]   += 1;

  TString result;
  
  for (Int_t i=0; i<MCalibrationCam::gkNumPulserColors; i++)
    {
      switch (i)
        {
        case MCalibrationCam::kGREEN:
          if (number[i] > 0.1)
            {
              result += number[i];
              result += "GREEN";
            }
          break;
        case MCalibrationCam::kBLUE:
          if (number[i] > 0.1)
            {
              result += number[i];
              result += "BLUE";
            }
          break;
        case MCalibrationCam::kUV:
          if (number[i] > 0.1)
            {
              result += number[i];
              result += "UV";
            }
          break;
        case MCalibrationCam::kCT1:
          if (number[i] > 0.1)
            result += "CT1";
          break;
        }
    }
  return result.Data();
}
