/* ======================================================================== *\
!
! *
! * 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   02/2004 <mailto:markus@ifae.es>
!
!   Copyright: MAGIC Software Development, 2000-2004
!
!
\* ======================================================================== */
/////////////////////////////////////////////////////////////////////////////
//                                                               
// MHCalibrationCam                                               
//
//
/////////////////////////////////////////////////////////////////////////////
#include "MHCalibrationCam.h"

#include <TVirtualPad.h>
#include <TCanvas.h>
#include <TPad.h>
#include <TText.h>
#include <TPaveText.h>

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

#include "MHGausEvents.h"

#include "MGeomCam.h"
#include "MGeomPix.h"

ClassImp(MHCalibrationCam);

using namespace std;

const Int_t   MHCalibrationCam::fgPulserFrequency          = 500;
// --------------------------------------------------------------------------
//
// Default Constructor. 
//
// Initializes and sets owner of:
// - fHiGainArray, fLoGainArray
// - fAverageHiGainAreas, fAverageLoGainAreas
// - fAverageHiGainSectors, fAverageLoGainSectors
//
// Initializes:
// - fPulserFrequency to fgPulserFrequency
//
MHCalibrationCam::MHCalibrationCam(const char *name, const char *title)
{
    fName  = name  ? name  : "MHCalibrationCam";
    fTitle = title ? title : "Class to fill the calibration histograms ";

    fHiGainArray = new TObjArray;
    fHiGainArray->SetOwner();
    
    fLoGainArray = new TObjArray;
    fLoGainArray->SetOwner();

    fAverageHiGainAreas = new TObjArray;
    fAverageHiGainAreas->SetOwner();

    fAverageLoGainAreas = new TObjArray;
    fAverageLoGainAreas->SetOwner();

    fAverageHiGainSectors = new TObjArray;
    fAverageHiGainSectors->SetOwner();

    fAverageLoGainSectors = new TObjArray;
    fAverageLoGainSectors->SetOwner();

    SetPulserFrequency();
}

// --------------------------------------------------------------------------
//
// Deletes the TClonesArray of:
// - fHiGainArray, fLoGainArray
// - fAverageHiGainAreas, fAverageLoGainAreas
// - fAverageHiGainSectors, fAverageLoGainSectors
//
MHCalibrationCam::~MHCalibrationCam()
{
  delete fHiGainArray;
  delete fLoGainArray;

  delete fAverageHiGainAreas;
  delete fAverageLoGainAreas;

  delete fAverageHiGainSectors;
  delete fAverageLoGainSectors;
}

// --------------------------------------------------------------------------
//
// Get i-th High Gain pixel (pixel number)
//
MHGausEvents &MHCalibrationCam::operator[](UInt_t i)
{
  return *static_cast<MHGausEvents*>(fHiGainArray->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th High Gain pixel (pixel number)
//
const MHGausEvents &MHCalibrationCam::operator[](UInt_t i) const
{
  return *static_cast<MHGausEvents*>(fHiGainArray->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th Low Gain pixel (pixel number)
//
MHGausEvents  &MHCalibrationCam::operator()(UInt_t i)
{
  return *static_cast<MHGausEvents*>(fLoGainArray->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th Low Gain pixel (pixel number)
//
const MHGausEvents  &MHCalibrationCam::operator()(UInt_t i) const
{
  return *static_cast<MHGausEvents*>(fLoGainArray->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th High Gain pixel Area (area number)
//
MHGausEvents  &MHCalibrationCam::GetAverageHiGainArea(UInt_t i)
{
  return *static_cast<MHGausEvents*>(fAverageHiGainAreas->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th High Gain pixel Area (area number)
//
const MHGausEvents  &MHCalibrationCam::GetAverageHiGainArea(UInt_t i) const
{
  return *static_cast<MHGausEvents *>(fAverageHiGainAreas->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th Low Gain pixel Area (area number)
//
MHGausEvents  &MHCalibrationCam::GetAverageLoGainArea(UInt_t i)
{
  return *static_cast<MHGausEvents*>(fAverageLoGainAreas->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th Low Gain pixel Area (area number)
//
const MHGausEvents  &MHCalibrationCam::GetAverageLoGainArea(UInt_t i) const
{
  return *static_cast<MHGausEvents*>(fAverageLoGainAreas->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th High Gain Sector (sector number)
//
MHGausEvents  &MHCalibrationCam::GetAverageHiGainSector(UInt_t i)
{
  return *static_cast<MHGausEvents*>(fAverageHiGainSectors->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th High Gain Sector (sector number)
//
const MHGausEvents  &MHCalibrationCam::GetAverageHiGainSector(UInt_t i) const
{
  return *static_cast<MHGausEvents*>(fAverageHiGainSectors->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th Low Gain Sector (sector number)
//
MHGausEvents  &MHCalibrationCam::GetAverageLoGainSector(UInt_t i)
{
  return *static_cast<MHGausEvents*>(fAverageLoGainSectors->UncheckedAt(i));
}

// --------------------------------------------------------------------------
//
// Get i-th Low Gain Sector (sector number)
//
const MHGausEvents  &MHCalibrationCam::GetAverageLoGainSector(UInt_t i) const
{
  return *static_cast<MHGausEvents*>(fAverageLoGainSectors->UncheckedAt(i));
}


// --------------------------------------------------------------------------
//
// Our own clone function is necessary since root 3.01/06 or Mars 0.4
// I don't know the reason. 
//
// Creates new MHCalibrationCam
// Deletes the TObjArray's and Clones them individually
// Copies the TArray's
//
TObject *MHCalibrationCam::Clone(const char *) const
{

  const Int_t nhi   = fHiGainArray->GetEntries();
  const Int_t nlo   = fLoGainArray->GetEntries();
  const Int_t navhi = fAverageHiGainAreas->GetEntries();
  const Int_t navlo = fAverageLoGainAreas->GetEntries();
  const Int_t nsehi = fAverageHiGainSectors->GetEntries();
  const Int_t nselo = fAverageLoGainSectors->GetEntries();
  
  //
  // FIXME, this might be done faster and more elegant, by direct copy.
  //
  MHCalibrationCam *cam = new MHCalibrationCam();

  cam->fHiGainArray->Expand(nhi);
  cam->fLoGainArray->Expand(nlo);
  cam->fAverageHiGainAreas->Expand(navhi);
  cam->fAverageLoGainAreas->Expand(navlo);
  cam->fAverageHiGainSectors->Expand(nsehi);
  cam->fAverageLoGainSectors->Expand(nselo);

  for (int i=0; i<nhi; i++)
    {
      delete (*cam->fHiGainArray)[i];
      (*cam->fHiGainArray)[i] = (*fHiGainArray)[i]->Clone();
    }
  for (int i=0; i<nlo; i++)
    {
      delete (*cam->fLoGainArray)[i];
      (*cam->fLoGainArray)[i] = (*fLoGainArray)[i]->Clone();
    }
  for (int i=0; i<navhi; i++)
    {
      delete (*cam->fAverageHiGainAreas)[i];
      (*cam->fAverageHiGainAreas)[i] = (*fAverageHiGainAreas)[i]->Clone();
    }
  for (int i=0; i<navlo; i++)
    {
      delete (*cam->fAverageLoGainAreas)[i];
      (*cam->fAverageLoGainAreas)[i] = (*fAverageLoGainAreas)[i]->Clone();
    }
  for (int i=0; i<nsehi; i++)
    {
      delete (*cam->fAverageHiGainSectors)[i];
      (*cam->fAverageHiGainSectors)[i] = (*fAverageHiGainSectors)[i]->Clone();
    }
  for (int i=0; i<nselo; i++)
    {
      delete (*cam->fAverageLoGainSectors)[i];
      (*cam->fAverageLoGainSectors)[i] = (*fAverageLoGainSectors)[i]->Clone();
    }

  cam->fAverageAreaNum         = fAverageAreaNum;
  cam->fAverageAreaSat         = fAverageAreaSat;
  cam->fAverageAreaSigma       = fAverageAreaSigma;      
  cam->fAverageAreaSigmaErr    = fAverageAreaSigmaErr;   
  cam->fAverageAreaRelSigma    = fAverageAreaRelSigma;
  cam->fAverageAreaRelSigmaErr = fAverageAreaRelSigmaErr;   
  cam->fAverageSectorNum       = fAverageSectorNum;      

  return cam;
}

// --------------------------------------------------------------------------
//
// Dummy, needed by MCamEvent
//
Bool_t MHCalibrationCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
{
  return kTRUE;
}

// --------------------------------------------------------------------------
//
// What MHCamera needs in order to draw an individual pixel in the camera
//
void MHCalibrationCam::DrawPixelContent(Int_t idx) const
{
}

// -----------------------------------------------------------------------------
// 
// Default draw:
//
// Displays the averaged areas, both High Gain and Low Gain 
//
// The following options can be chosen:
//
// Calls the Draw of the fAverageHiGainAreas and fAverageLoGainAreas objects with options
//
void MHCalibrationCam::Draw(const Option_t *opt)
{

  const Int_t nareas = fAverageHiGainAreas->GetEntries();
  if (nareas == 0)
    return;

  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
  pad->SetBorderMode(0);

  pad->Divide(2,nareas);

  for (Int_t i=0; i<nareas;i++) 
    {
      pad->cd(2*(i+1)-1);
      GetAverageHiGainArea(i).Draw(opt);

      if (!fAverageAreaSat[i])
        DrawAverageSigma(fAverageAreaSat[i], i,
                         fAverageAreaSigma[i],    fAverageAreaSigmaErr[i],
                         fAverageAreaRelSigma[i], fAverageAreaRelSigmaErr[i]);

      pad->cd(2*(i+1));
      GetAverageLoGainArea(i).Draw(opt);
      
      if (fAverageAreaSat[i])
        DrawAverageSigma(fAverageAreaSat[i], i,
                         fAverageAreaSigma[i], fAverageAreaSigmaErr[i],
                         fAverageAreaRelSigma[i], fAverageAreaRelSigmaErr[i]);
    }
}

// -----------------------------------------------------------------------------
// 
// Default draw:
//
// Displays a TPaveText with the re-normalized sigmas of the average area
//
void MHCalibrationCam::DrawAverageSigma(Bool_t sat, Bool_t inner,
                                              Float_t sigma, Float_t sigmaerr,
                                              Float_t relsigma, Float_t relsigmaerr) const 
{
  
  if (sigma != 0)
    {
      
      TPad *newpad = new TPad("newpad","transparent",0,0,1,1);
      newpad->SetFillStyle(4000);
      newpad->Draw();
      newpad->cd();
      
      TPaveText *text = new TPaveText(sat? 0.1 : 0.35,0.7,sat ? 0.4 : 0.7,1.0);
      text->SetTextSize(0.07);
      const TString line1 = Form("%s%s%s",inner ? "Outer" : "Inner",
                                 " Pixels ", sat ? "Low Gain" : "High Gain");
      TText *txt1 = text->AddText(line1.Data());
      const TString line2 = Form("#sigma per pix: %2.2f #pm %2.2f",sigma,sigmaerr);
      TText *txt2 = text->AddText(line2.Data());
      const TString line3 = Form("Rel. #sigma per pix: %2.2f #pm %2.2f",relsigma,relsigmaerr);
      TText *txt3 = text->AddText(line3.Data());
      text->Draw("");
      
      text->SetBit(kCanDelete);
      txt1->SetBit(kCanDelete);
      txt2->SetBit(kCanDelete);
      txt3->SetBit(kCanDelete);
      newpad->SetBit(kCanDelete);
    }
}

