/* ======================================================================== *\
!
! *
! * 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, 8/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
!
!   Copyright: MAGIC Software Development, 2000-2004
!
!
\* ======================================================================== */

/////////////////////////////////////////////////////////////////////////////
//
//  MJob
//
// A base class for jobs
//
/////////////////////////////////////////////////////////////////////////////
#include "MJob.h"

#include <TEnv.h>
#include <TFile.h>
#include <TSystem.h>

#include "MIter.h"

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

#include "MEvtLoop.h"

ClassImp(MJob);

using namespace std;

// --------------------------------------------------------------------------
//
// Default constructor. 
//
// Sets fRuns to 0, fExtractor to NULL, fDataCheck to kFALSE
//
MJob::MJob(const char *name, const char *title) : fEnv(0), fOverwrite(kFALSE), fMaxEvents(0)
{
    fName  = name  ? name  : "MJob";
    fTitle = title ? title : "Base class for jobs";
}

MJob::~MJob()
{
    if (fEnv)
        delete fEnv;
}

Bool_t MJob::SetEnv(const char *env, const char *prefix)
{
    if (fEnv)
    {
        delete fEnv;
        fEnv = 0;
    }

    const Bool_t fileexist = !gSystem->AccessPathName(env, kFileExists);
    if (!fileexist)
    {
        *fLog << err << "ERROR - Resource file '" << env << "' not found... no resources applied." << endl;
        return kFALSE;
    }

    fEnv = new TEnv(env);

    fEnvPrefix = prefix;
    if (!prefix)
        fEnvPrefix = fName.First(' ')>0 ? fName(0, fName.First(' ')) : fName;

    if (fEnvPrefix.EndsWith("."))
        fEnvPrefix.Remove(fEnvPrefix.Length()-1);

    return kTRUE;
}

void MJob::FixPath(TString &path) const
{
    path.ReplaceAll("\015", "");

    if (path==(TString)"/")
        return;

    if (path.EndsWith("/"))
        path.Remove(path.Length()-1);
}

void MJob::SetPathOut(const char *path)
{
    fPathOut = path;
    FixPath(fPathOut);
}

void MJob::SetPathIn(const char *path)
{
    fPathIn = path;
    FixPath(fPathIn);
}

void MJob::SetPathData(const char *path)
{
    fPathData = path;
    FixPath(fPathData);
}

Int_t MJob::GetEnv(const char *name, Int_t dflt) const
{
    return GetEnvValue(*fEnv, fEnvPrefix, name, dflt); //    return fEnv->GetValue(Form("%s%s", fEnvPrefix.Data(), name), dflt);
}

Double_t MJob::GetEnv(const char *name, Double_t dflt) const
{
    return GetEnvValue(*fEnv, fEnvPrefix, name, dflt); //    return fEnv->GetValue(Form("%s%s", fEnvPrefix.Data(), name), dflt);
}

const char *MJob::GetEnv(const char *name, const char *dflt) const
{
    return GetEnvValue(*fEnv, fEnvPrefix, name, dflt); //fEnv->GetValue(Form("%s%s", fEnvPrefix.Data(), name), dflt);
}

Bool_t MJob::HasEnv(const char *name) const
{
    return IsEnvDefined(*fEnv, fEnvPrefix, name, fEnvDebug);//fEnv->Lookup(Form("%s%s", fEnvPrefix.Data(), name));
}

Bool_t MJob::CheckEnv()
{
    if (!fEnv)
        return kTRUE;

    TString p;
    p = GetEnv("PathOut", "");
    if (!p.IsNull())
        SetPathOut(p);

    p = GetEnv("PathIn", "");
    if (!p.IsNull())
        SetPathIn(p);

    p = GetEnv("PathData", "");
    if (!p.IsNull())
        SetPathData(p);

    SetMaxEvents(GetEnv("MaxEvents", fMaxEvents));
    SetOverwrite(GetEnv("Overwrite", fOverwrite));

    return CheckEnvLocal();
}

Bool_t MJob::SetupEnv(MEvtLoop &loop) const
{
    if (!fEnv)
        return kTRUE;

    return loop.ReadEnv(*fEnv, fEnvPrefix, fEnvDebug) ? kTRUE : kFALSE;
}

Bool_t MJob::WriteContainer(TCollection &list) const
{
    if (!gFile)
    {
        *fLog << err << dbginf << "ERROR - No file open (gFile==0)" << endl;
        return kFALSE;
    }

    MIter Next(&list);
    MParContainer *o=0;
    while ((o=Next()))
    {
        *fLog << inf << " - Writing " << o->GetDescriptor() << "..." << flush;
        if (o->Write(o->GetName())<=0)
        {
            *fLog << err << dbginf << "ERROR - Writing " << o->GetDescriptor() << " to file " << gFile->GetName() << endl;
            return kFALSE;
        }
        *fLog << "ok." << endl;
    }
    return kTRUE;
}

Bool_t MJob::ReadContainer(TCollection &list) const
{
    if (!gFile)
    {
        *fLog << err << dbginf << "ERROR - No file open (gFile==0)" << endl;
        return kFALSE;
    }

    MIter Next(&list);
    MParContainer *o=0;
    while ((o=Next()))
    {
        *fLog << inf << " - Reading " << o->GetDescriptor() << "..." << flush;
        if (o->Read(o->GetName())<=0)
        {
            *fLog << err << dbginf << "ERROR - Reading " << o->GetDescriptor() << " from file " << gFile->GetName() << endl;
            return kFALSE;
        }
        *fLog << "ok." << endl;
    }
    return kTRUE;
}
