#include "TMDisplayingCErrorShowEC.h"
#include "TMControlSPD.h"
#include "SPDMood.h"
#include "AliITSRawStreamSPD.h"
#include <TGButton.h>
#include <TGTextView.h>
#include <TCanvas.h>

ClassImp(TMDisplayingCErrorShowEC)

//_____________________________________________________________________
TMDisplayingCErrorShowEC::TMDisplayingCErrorShowEC(const Char_t *frameName, const TGWindow *p, UInt_t width, UInt_t height, TMHistogramming *hist, UInt_t id, UInt_t plotNr, UInt_t cloneId) :
  TMDisplaying(frameName,p,width,height,hist,id,plotNr,cloneId,kTRUE)
{
  gClient->GetColorByName("green", green);
  gClient->GetColorByName("gray", gray);

  CreateTopFrame();
  CreateButtonFrame();
  CreateBottomFrame();

  MapSubwindows();
  Resize();
  MapWindow();

  TCanvas *canv = fTheCanvas->GetCanvas();
  fHist->Draw(canv);
  Update();
}
//_____________________________________________________________________
TMDisplayingCErrorShowEC::~TMDisplayingCErrorShowEC() {}
//_____________________________________________________________________
void TMDisplayingCErrorShowEC::CreateButtonFrame() {
  TGCompositeFrame *tf = new TGCompositeFrame(this, 50, 21, kHorizontalFrame | kFixedSize);
  AddFrame(tf, new TGLayoutHints(kLHintsExpandX, 0,0,0,0));
  fShowErrorCodesButton = new TGTextButton(tf,"Show Error Codes",ADD_ID_START);
  fShowErrorCodesButton->Associate(this);
  tf->AddFrame(fShowErrorCodesButton, new TGLayoutHints(kLHintsNormal, 0,0,0,0));
}
//______________________________________________________________________
Bool_t TMDisplayingCErrorShowEC::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) {
  //  printf("%d,%ld,%ld\n",GET_MSG(msg),parm1,parm2);
  if (fPleaseWait) {
    time_t stamp = time(NULL);
    TString stampMsg = Form("%s",ctime(&stamp));
    stampMsg.ReplaceAll("\n","");
    printf("Busy - Please try again... (Time %s)\n",stampMsg.Data());
    return kTRUE;
  }
  fPleaseWait = kTRUE;
  switch(GET_MSG(msg)) {
  case kC_COMMAND :
    switch (GET_SUBMSG(msg)) {

    case kCM_BUTTON :
      if (parm1==ADD_ID_START) {
	TMControlSPD::Instance()->HoldRunning();
	ProcessOpenCErrorCodesFrame();
	TMControlSPD::Instance()->ContinueRunning();
	fPleaseWait = kFALSE;
	return kTRUE;
      }
    }
  }
  fPleaseWait = kFALSE;
  return TMDisplaying::ProcessMessage(msg,parm1,parm2);
}
//_____________________________________________________________________
void TMDisplayingCErrorShowEC::ProcessOpenCErrorCodesFrame() {
  TGMainFrame *mF = new TGMainFrame(gClient->GetRoot(),300,520);
  mF->SetWindowName("Consistency Error Codes");

  TGTextView *tv =  new TGTextView(mF, 305, 340, kHorizontalFrame | kFixedSize);

  mF->AddFrame(tv, new TGLayoutHints(kLHintsExpandX  | kLHintsExpandY,0,0,0,0));

  for (UInt_t err=0; err<AliITSRawStreamSPDErrorLog::kNrErrorCodes; err++) {
    TString msg = Form(" %d. %s",err,AliITSRawStreamSPD::GetErrorName(err));
    tv->AddLine(msg.Data());
  }
  tv->Update();

  mF->MapSubwindows();
  mF->Resize();
  mF->MapWindow();
}
