/* ======================================================================== *\
!
! *
! * 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): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
!
!   Copyright: MAGIC Software Development, 2000-2001
!
!
\* ======================================================================== */

//////////////////////////////////////////////////////////////////////////////
//                                                                          //
//  MRawSocketRead                                                            //
//                                                                          //
//  This tasks reads the raw binary file like specified in the TDAS???      //
//  and writes the data in the corresponding containers which are           //
//  either retrieved from the parameter list or created and added.          //
//                                                                          //
//  Input Containers:                                                       //
//   -/-                                                                    //
//                                                                          //
//  Output Containers:                                                      //
//   MRawRunHeader, MRawEvtHeader, MRawEvtData, MRawCrateArray, MRawEvtTime //
//                                                                          //
//////////////////////////////////////////////////////////////////////////////
#include "MRawSocketRead.h"

#include <TMutex.h>

#include "MReadSocket.h"

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

#include "MParList.h"
#include "MTaskList.h"
#include "MEvtLoop.h"

#include "MTime.h"
#include "MRawRunHeader.h"
#include "MRawEvtHeader.h"
#include "MRawEvtData.h"
#include "MRawCrateData.h"
#include "MRawCrateArray.h"

ClassImp(MRawSocketRead);

using namespace std;

// --------------------------------------------------------------------------
//
// Default constructor. It tries to open the given file.
//
MRawSocketRead::MRawSocketRead(const char *name, const char *title)
    : fIn(NULL)
{
    fName  = name  ? name  : "MRawSocketRead";
    fTitle = title ? title : "Task to read DAQ binary data from tcp/ip socket";

    fIn = new MReadSocket(7000);
    fMutex = new TMutex;
}

// --------------------------------------------------------------------------
//
// Destructor. Delete input stream.
//
MRawSocketRead::~MRawSocketRead()
{
    delete fMutex;
    delete fIn;
}

// --------------------------------------------------------------------------
//
// The PreProcess of this task checks for the following containers in the
// list:
//   MRawRunHeader <output>   if not found it is created
//   MRawEvtHeader <output>   if not found it is created
//   MRawEvtData <output>     if not found it is created
//   MRawCrateArray <output>  if not found it is created
//   MRawEvtTime <output>     if not found it is created (MTime)
//
// If all containers are found or created the run header is read from the
// binary file and printed.  If the Magic-Number (file identification)
// doesn't match we stop the eventloop.
//
// Now the EvtHeader and EvtData containers are initialized.
//
Int_t MRawSocketRead::PreProcess(MParList *pList)
{
    //
    //  check if all necessary containers exist in the Parameter list.
    //  if not create one and add them to the list
    //
    fRawRunHeader = (MRawRunHeader*)pList->FindCreateObj("MRawRunHeader");
    if (!fRawRunHeader)
        return kFALSE;

    fRawEvtHeader = (MRawEvtHeader*)pList->FindCreateObj("MRawEvtHeader");
    if (!fRawEvtHeader)
        return kFALSE;

    fRawEvtData = (MRawEvtData*)pList->FindCreateObj("MRawEvtData");
    if (!fRawEvtData)
        return kFALSE;

    fRawCrateArray = (MRawCrateArray*)pList->FindCreateObj("MRawCrateArray");
    if (!fRawCrateArray)
        return kFALSE;

    fRawEvtTime = (MTime*)pList->FindCreateObj("MTime", "MRawEvtTime");
    if (!fRawEvtTime)
        return kTRUE;

    fParList = pList;
    fRunNumber = (UInt_t)-1;
    fEvtNumber = (UInt_t)-1;

    /*
    MEvtLoop *loop=(MEvtLoop*)pList->FindObject("Evtloop");
    if (loop)
        loop->SetProgressBar((TGProgressBar*)NULL);
     */
    return kTRUE;
}

Int_t MRawSocketRead::Do()
{
    /*
    sprintf(report_str, " %8.8d %8.8d %6.6d",
    run_header->RunNumber, run.event_number,
    time.tv_sec - run.time_start_secs);
    if (send(sd, report_str, strlen(report_str), flags) == -1) {
    return -1;
    }

    sprintf(report_str, " %6.1f %6.1f %6.6d %7.4f %8.8d %6.6d ",
    trigrate_hz, storerate_hz, storerate_kbps, gammarate_hz,
    diskspace_kb, remtime_sec);
    if (send(sd, report_str, strlen(report_str), flags) == -1) {
    return -1;
    }
    */
    char dummy[126];
    fIn->read(dummy, 4);   // \nEVT

    if (!(dummy[0]=='\n' && dummy[1]=='E' && dummy[2]=='V' &&dummy[3]=='T'))
    {
        *fLog << warn << "EVT tag not found. Stream out of sync. Please try to restart..." << endl;
        // FIXME: Synchronization missing...
        return kFALSE;
    }

    char size[6] = {0,0,0,0,0,0};
    fIn->read(size, 5);
    fIn->read(dummy, 126); //00000[CC-DATA]\n

    /*
    int numevt;
    sscanf(dummy,  "%*s %*d %*d %*d %*d %*d %*d %*d "
           "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
           "%d %*d %*f %*f %*d %*f %*d %*d", &numevt);
    */

    //
    // Read RUN HEADER (see specification) from input stream
    //
    fLog->SetNullOutput();
    fRawRunHeader->ReadEvt(*fIn);
    fLog->SetNullOutput(kFALSE);

    if (fRawRunHeader->GetMagicNumber()!=kMagicNumber && fRawRunHeader->GetMagicNumber()!=kMagicNumber+1)
    {
        *fLog << err << "Error: Wrong Magic Number (0x" << hex << fRawRunHeader->GetMagicNumber() << "): Not a Magic File!" << endl;
        return kFALSE;
    }

    if (fRunNumber!=fRawRunHeader->GetRunNumber())
    {
        fRawRunHeader->Print();

        MTaskList *tlist = (MTaskList*)fParList->FindObject("MTaskList");
        if (!tlist)
        {
            *fLog << err << dbginf << "ERROR - Task List not found in Parameter List." << endl;
            return kFALSE;
        }

        if (!tlist->ReInit())
            return kFALSE;

        fRunNumber = fRawRunHeader->GetRunNumber();
    }

    if (atoi(size)==fRawRunHeader->GetNumTotalBytes())
        return kCONTINUE;

    //
    // Give the run header information to the 'sub-classes'
    //
    fRawEvtHeader->Init(fRawRunHeader, fRawEvtTime);
    fRawEvtData  ->Init(fRawRunHeader);

    //
    //  Read in the next EVENT HEADER (see specification),
    // if there is no next event anymore stop eventloop
    //
    if (!fRawEvtHeader->ReadEvt(*fIn))
        return kFALSE;

    //
    //  Get number of crates from the run header
    //
    const UShort_t nc = fRawRunHeader->GetNumCrates();

    //
    // Delete arrays which stores the pixel information (time slices)
    //
    fRawEvtData->ResetPixels();

    //
    // clear the TClonesArray which stores the Crate Information
    // and create a new array of the correct size
    //
    fRawCrateArray->SetSize(nc);

    //
    // read the CRATE DATA (see specification) from file
    //
    for (int i=0; i<nc; i++)
    {
        fRawCrateArray->GetEntry(i)->ReadEvt(*fIn);
        if (!*fIn)
            return kFALSE;

        fRawEvtData->ReadEvt(*fIn);
        if (!*fIn)
            return kFALSE;
    }

    if (fEvtNumber==fRawEvtHeader->GetDAQEvtNumber())
        return kCONTINUE;

    fEvtNumber=fRawEvtHeader->GetDAQEvtNumber();

    //*fLog << dbg << "Evt " << fRawEvtHeader->GetDAQEvtNumber() << endl;

    return kTRUE;
}

// --------------------------------------------------------------------------
//
// The Process reads one event from the binary file:
//  - The event header is read
//  - the run header is read
//  - all crate information is read
//  - the raw data information of one event is read
//
Int_t MRawSocketRead::Process()
{
    Lock();
    Int_t rc = Do();
    UnLock();
    return rc;
}

Int_t MRawSocketRead::Lock()
{
    return fMutex->Lock();
}

Int_t MRawSocketRead::UnLock()
{
    return fMutex->UnLock();
}
