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

 Copyright 2012 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 "TemporaryObject.h"

#include "IconFactory.h"
#include "Request.h"
#include "MvIconLanguage.h"
#include "IconClass.h"
#include "Dependancy.h"

#include "mars.h"

static std::string next_name()
{
    static int i = 0;
    char buf[80];
    sprintf(buf, "Temp%04d", i++);
    return buf;
}

TemporaryObject::TemporaryObject(IconObject* ref, const Request& r, const IconClass* c) :
    IconObject(nullptr, c ? *c : IconClass::find(r.getVerb()), next_name(), nullptr),
    ref_(ref),
    request_(r)
{
    std::cout << "-->  TemporaryObject::TemporaryObject() for" << *ref_ << std::endl;
    r.print();
    std::cout << "<--  TemporaryObject::TemporaryObject() for" << *ref_ << std::endl;
}

TemporaryObject::~TemporaryObject()
{
    std::cout << "TemporaryObject::~TemporaryObject() for " << *ref_ << std::endl;
}

Folder* TemporaryObject::parent() const
{
    return ref_->parent();
}

void TemporaryObject::createFiles()
{
}

Request TemporaryObject::request() const
{
    request_.print();
    return language().expand(request_, EXPAND_NO_DEFAULT | EXPAND_2ND_NAME);
}

void TemporaryObject::setRequest(const Request& r)
{
    request_ = r;
}

Path TemporaryObject::pathForShellTask() const
{
    const char* path = request_("PATH");
    if (path) {
        const char* path = request_("PATH");
        return std::string(path);
    }
    return std::string("/dev/null");
}

Path TemporaryObject::path() const
{
    return std::string("/dev/null");
}


Path TemporaryObject::dotPath() const
{
    return std::string("/dev/null");
}

Path TemporaryObject::embeddedPath() const
{
    return std::string("/dev/null");
}

std::string TemporaryObject::fullName() const
{
    return ref_->fullName() + "/" + name();
}
std::string TemporaryObject::relativeName(IconObject* other) const
{
    return ref_->relativeName(other);
}

std::string TemporaryObject::makeFullName(const std::string& name) const
{
    return ref_->makeFullName(name);
}

Folder* TemporaryObject::embeddedFolder(const std::string& n, bool create) const
{
    return ref_->embeddedFolder(n, create);
}

Folder* TemporaryObject::embeddedFolder(bool create) const
{
    return ref_->embeddedFolder(create);
}

#if 0
Log& TemporaryObject::log()
{
	return ref_->log();
}
#endif

bool TemporaryObject::rename(const std::string& s)
{
    name_ = s;
    return true;
}

bool TemporaryObject::renamable() const
{
    return true;
}

bool TemporaryObject::temporary() const
{
    return true;
}
