/***************************** 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 "MacroToPythonConvert.h"

#include <iostream>

#include "MvMiscellaneous.h"
#include "Path.h"

std::string  MacroToPythonConvert::resolveMacroPath(const std::string& inPath)
{
    auto fMacro = Path(inPath);

    if (fMacro.str().find(metview::metviewRootDir()) != 0) {
        auto rootDir = Path(metview::metviewRootDir());
        fMacro = rootDir.add(inPath);
    }

    return fMacro.str();
}

int MacroToPythonConvert::convert(const std::string& inPath, bool resolveInPath,
                           std::string& outPath)
{
    errText_.clear();

    auto fMacro = Path(inPath);

    if (resolveInPath) {
        if (fMacro.str().find(metview::metviewRootDir()) != 0) {
            auto rootDir = Path(metview::metviewRootDir());
            fMacro = rootDir.add(inPath);
        }
    }

    auto fPy = Path(outPath);
    if (fPy.str().empty()) {
        std::string name, suffix;
        fMacro.nameAndSuffix(name, suffix);
        name += ".py";
        fPy = fMacro.directory().add(name);
        fPy = fPy.directory().add(fPy.uniqueNameInDir());
        outPath = fPy.str();
    }

    std::string cmd = "$METVIEW_BIN/macro2py \"" + fMacro.str() +
            + "\" \"" + fPy.str() + "\"";

    cmd += needHeader_?" 1":" 0";
    cmd += needWarnings_?" 1":" 0";
    cmd += needLicense_?" 1":" 0";
    cmd += needBlack_?" 1":" 0";

    std::stringstream outStr, errStr;
    int ret = metview::shellCommand(cmd, outStr, errStr);
    errText_ = errStr.str();
    outText_ = outStr.str();
    return ret;
}
