/***************************** LICENSE START ***********************************

 Copyright 2014 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "Log.h"

#include <fstream>
#include "fstream_mars_fix.h"

#include <cstdio>
#include <cerrno>
#include <ctime>
#include <cstring>

#include "Folder.h"
#include "TeeStream.h"
#include "IconObject.h"


// which platform require this one?
// (not SGI, and Linux get compiler errors
//  because of different types...!)
// extern char *sys_errlist[];
// extern const int sys_nerr;

// static std::string logTimeStamp();

Log::Log(IconObject* o) :
    path_(::marstmp()),
    object_(o)
{
}

Log::~Log()
{
    path_.remove();
}

std::ostream& Log::global()
{
    static std::ostream* g = nullptr;
    if (g == nullptr) {
        g = &std::cout;  // Avoid recursion
        std::string p = Folder::top()->logPath().str();
        g = new std::ofstream(p.c_str(), std::ios::app);
        // Folder::top()->showLog();
    }
    return *g;
}

Log::operator std::ostream&()
{
    if (tee_.get() == nullptr) {
        out_ = std::unique_ptr<std::ostream>(new std::ofstream(path_.str().c_str(), std::ios::app));
        tee_ = std::unique_ptr<std::ostream>(new TeeStream(global(), *out_));
    }

    // Add time stamp
    //*out_ << logTimeStamp();

    global() << "[" << object_->name() << "] ";

    return *tee_;
}

const Path& Log::path()
{
    return path_;
}

std::ostream& Log::syserr(std::ostream& s)
{
    int e = errno;

    if (e > 0)
        s << " (" << strerror(e) << ") ";
    else
        s << " (errno = " << e << ") ";
    return s;
}

std::ostream& Log::error(IconObject* o)
{
    return find(o);
}

std::ostream& Log::info(IconObject* o)
{
    return find(o);

    // if(o == 0) o = Folder::top();
    // return o->log() << "A";
}

std::ostream& Log::warning(IconObject* o)
{
    return find(o);
}

std::ostream& Log::info(const std::string& p)
{
    return global() << "[" << p << "] ";
}

std::ostream& Log::warning(const std::string& p)
{
    return info(p);
}

std::ostream& Log::error(const std::string& p)
{
    return info(p);
}

std::ostream& Log::find(IconObject* o)
{
    if (o == nullptr)
        o = Folder::top();
    return o->log();
}

/*std::string logTimeStamp()
{
    time_t t = time(0);
        struct tm* now = localtime(&t);
    char buf[7];
    strftime(buf, sizeof(buf),"%H:%M",now);

    string str;
    str=string(buf);
    return str;
}*/
