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

 Copyright 2013 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 <fstream>
#include <sstream>
#include <string>
#include "fstream_mars_fix.h"

#include "Metview.h"

#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

#include "MvScm.h"


class Base : public MvService
{
protected:
    Base(const char* a) :
        MvService(a) {}
};

class ScmRun : public Base
{
public:
    ScmRun() :
        Base("SCM_RUN") { ftmp = marstmp(); }
    void serve(MvRequest&, MvRequest&);

protected:
    void shellCommand(std::string&, std::stringstream&, std::stringstream&);

    std::string ftmp;
};

void ScmRun::shellCommand(std::string& command, std::stringstream& out, std::stringstream& err)
{
    FILE* in;
    char cbuf[512];

    std::string cmd = command + " 2>" + ftmp;

    if (!(in = popen(cmd.c_str(), "r"))) {
        return;
    }

    while (fgets(cbuf, sizeof(cbuf), in) != nullptr) {
        out << cbuf;
    }

    pclose(in);


    if (!(in = fopen(ftmp.c_str(), "r"))) {
        return;
    }

    while (fgets(cbuf, sizeof(cbuf), in) != nullptr) {
        err << cbuf;
    }

    fclose(in);
}

void ScmRun::serve(MvRequest& in, MvRequest& out)
{
    std::cout << "--------------ScmRun::serve() in--------------" << std::endl;
    in.print();

    std::string errTxt;

    // Find out scm script path
    std::string scmScript;
    char* mvbin = getenv("METVIEW_BIN");
    if (mvbin == nullptr) {
        setError(1, "ScmRun-> No METVIEW_BIN env variable is defined. Cannot locate script mv_scm_run!");
        return;
    }
    else {
        scmScript = std::string(mvbin) + "/mv_scm_run";
    }


    // Create  tmp dir for the flextra run
    std::string tmpPath;
    if (!metview::createWorkDir("scm", tmpPath, errTxt)) {
        setError(1, "ScmRun-> %s", errTxt.c_str());
        return;
    }

    // Scm exe
    std::string exe;
    if (!in.getPath("SCM_EXE_PATH", exe, true)) {
        setError(1, "ScmRun-> parameter SCM_EXE_PATH not defined");
        return;
    }
    if (exe.empty()) {
        exe = "_UNDEF_";
    }

    //---------------------------------------
    // Input data
    //---------------------------------------

    std::string data;
    if (!in.getPath("SCM_INPUT_DATA", "SCM_INPUT_DATA_PATH", data, true, errTxt)) {
        setError(1, "ScmRun-> %s", errTxt.c_str());
        return;
    }

    //-------------------------
    // Level num
    //-------------------------

    int levelNum = MvScm::modelLevelNum(data);
    if (levelNum == -1) {
        setError(1, "ScmRun-> Could not read number of levels from input file!");
        return;
    }

    std::stringstream sst;
    sst << levelNum;
    std::string nlev = sst.str();

    //-------------------------
    // Namelist
    //-------------------------

    std::string namelist;
    if (!in.getPath("SCM_NAMELIST", "SCM_NAMELIST_PATH", namelist, false, errTxt)) {
        setError(1, "ScmRun-> %s", errTxt.c_str());
        return;
    }

    //-------------------------
    // Vtable file
    //-------------------------

    std::string vtable;
    if (!in.getPath("SCM_VTABLE", "SCM_VTABLE_PATH", vtable, true, errTxt)) {
        setError(1, "ScmRun-> %s", errTxt.c_str());
        return;
    }
    if (vtable.empty()) {
        vtable = std::string("_UNDEF_");
    }

    //-------------------------
    // Rclim file
    //-------------------------

    std::string rclim;
    if (const char* cval = in("SCM_RCLIM_PATH")) {
        rclim = std::string(cval);
    }

    if (rclim.empty()) {
        rclim = std::string("_UNDEF_");
    }

    //-------------------------
    // COPY OUTPUT DATA
    //-------------------------

    std::string userResFile;

    const char* copyRes = in("SCM_COPY_OUTPUT_DATA");
    if (copyRes && strcmp(copyRes, "ON") == 0) {
        if (!in.getPath("SCM_OUTPUT_DATA_PATH", userResFile, false)) {
            setError(1, "ScmRun-> parameter SCM_OUTPUT_DATA_PATH not defined");
            return;
        }
    }

    //-------------------------
    // Run the model
    //-------------------------

    std::string resFileName = "scm_out.nc";
    std::string logFileName = "log.txt";
    std::string logFile = tmpPath + "/" + logFileName;

    // Run the scm script
    std::string cmd = scmScript + " \"" + tmpPath + "\" \"" + exe + "\" " + nlev + " \"" + data + "\" \"" + namelist + "\" \"" + vtable + "\" \"" + rclim + "\" \"" + logFileName + "\" \"" + resFileName + "\"";

    // marslog(LOG_INFO,"Execute command: %s",cmd.c_str());

    int ret = system(cmd.c_str());

    bool runFailed = false;

    // If the script failed read log file and
    // write it into LOG_EROR
    std::string err;
    if (ret == -1 || WEXITSTATUS(ret) != 0) {
        std::ifstream in(logFile.c_str());
        std::string line;

        if (WEXITSTATUS(ret) == 255) {
            setError(0, "ScmRun-> Warnings were generated during SCM run!");
        }
        else if (WEXITSTATUS(ret) == 1) {
            err = "ScmRun-> Failed to perform SCM run! ";
            runFailed = true;
        }
        else if (WEXITSTATUS(ret) > 1) {
            err = "ScmRun-> SCM run failed with exit code: ";
            err += WEXITSTATUS(ret);
            err += ". ";
            runFailed = true;
        }
    }

    // Log locations are always printed!!

    if (runFailed) {
        err += "Log files are available at: STDOUT ";
        err += logFile;
        err += "\n fort.20 ";
        err += tmpPath + "/fort.20";
        setError(1, err.c_str());
        return;
    }
    else {
        marslog(LOG_INFO, "Log files are available at:");
        marslog(LOG_INFO, " STDOUT  %s", logFile.c_str());
        std::string msg = tmpPath + "/fort.20";
        marslog(LOG_INFO, " fort.20 %s", msg.c_str());
    }

    //---------------------------
    // Merge the output files
    //---------------------------

    // At this point we have already copied progvar.nc into resFile in the script

    std::string resFile = tmpPath + "/" + resFileName;
    std::string diagFile = tmpPath + "/diagvar.nc";
    std::string diag2File = tmpPath + "/diagvar2.nc";

    if (MvScm::mergeOutFiles(resFile, diagFile, diag2File) == false) {
        setError(1, "ScmRun-> Could not merge SCM output files!");
        return;
    }

    //---------------------------------------------------
    // Copy the output into the user-defined location
    //---------------------------------------------------

    if (!userResFile.empty()) {
        const char* dn = mdirname(userResFile.c_str());
        cmd = "mkdir -p " + std::string(dn) + "; cp -f " + resFile + " " + userResFile;

        std::stringstream outStream;
        std::stringstream errStream;
        shellCommand(cmd, outStream, errStream);

        if (!errStream.str().empty()) {
            std::string err = "ScmRun-> Could not copy ouput file to target location! This command: ";
            err += cmd.c_str();
            err += " failed with this error: ";
            err += errStream.str();
            setError(1, err.c_str());
            return;
        }
    }

    //------------------------------------------
    // Set out request
    //------------------------------------------

    out = MvRequest("SCM_OUTPUT_DATA");
    out("PATH") = resFile.c_str();

    std::cout << "--------------ScmRun::serve() out--------------" << std::endl;
    out.print();
}


int main(int argc, char** argv)
{
    MvApplication theApp(argc, argv, "ScmRun");

    ScmRun scmRun;

    theApp.run();
}
