/***************************** 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 <fstream>
#include <iostream>
#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 RttovRun : public Base
{
public:
    RttovRun() :
        Base("RTTOV_RUN") {}
    void serve(MvRequest&, MvRequest&);
};

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

    std::string errTxt;

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


    // Create  tmp dir for the flextra run
    std::string tmpPath;
    if (!metview::createWorkDir("rttov", tmpPath, errTxt)) {
        std::string err = "RttovRun-> " + errTxt;
        setError(1, err.c_str());
        return;
    }

    // RttovRun exe
    std::string exe;
    if (!in.getPath("RTTOV_EXE_PATH", exe, true)) {
        setError(1, "RttovRun-> Error parameter RTTOV_EXE_PATH");
        return;
    }
    if (exe.empty()) {
        exe = "_UNDEF_";
    }

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

    std::string data;
    if (!in.getPath("RTTOV_INPUT_DATA", "RTTOV_INPUT_DATA_PATH", data, false, errTxt)) {
        std::string err = "RttovRun-> " + errTxt;
        setError(1, err.c_str());
        return;
    }

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

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

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

    //--------------------------------------
    // Sensor (channels + coefficients)
    //--------------------------------------

    const char* sensor = in("RTTOV_SENSOR");

    std::string ch = "_UNDEF_";
    std::string coeff = "_UNDEF_";
    if (sensor && strcmp(sensor, "CUSTOM") == 0) {
        // Channels file
        if (!in.getPath("RTTOV_CHANNELS", "RTTOV_CHANNELS_PATH", ch, true, errTxt)) {
            std::string err = "RttovRun-> " + errTxt;
            setError(1, err.c_str());
            return;
        }

        // Coeff file
        if (!in.getPath("RTTOV_COEFFICIENTS", "RTTOV_COEFFICIENTS_PATH", coeff, true, errTxt)) {
            std::string err = "RttovRun-> " + errTxt;
            setError(1, err.c_str());
            return;
        }
    }

    //-------------------------
    // Angles
    //-------------------------

    double sat_z, sat_az, solar_z, solar_az;

    in.getValue(sat_z, "RTTOV_SATELLITE_ZENITH_ANGLE");
    in.getValue(sat_az, "RTTOV_SATELLITE_AZIMUTH_ANGLE");
    in.getValue(solar_z, "RTTOV_SOLAR_ZENITH_ANGLE");
    in.getValue(solar_az, "RTTOV_SOLAR_AZIMUTH_ANGLE");

    //---------------------------
    // Prepare input file
    //---------------------------

    std::string inFile = tmpPath + "/rttov_in.txt";
    bool useOzone = (sensor && strcmp(sensor, "IASI") == 0) ? true : false;
    if (MvScm::createRttovInput(data, inFile, sat_z, sat_az, solar_z, solar_az, useOzone, errTxt) == false) {
        std::string err = "RttovRun-> Could not generate RTTOV input file! " + errTxt;
        setError(1, err.c_str());
        return;
    }

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

    std::string resFileName = "rttov_out.txt";
    std::string resFile = tmpPath + "/" + resFileName;

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

    // Run the scm script
    std::string cmd = rttovScript + " \"" + tmpPath + "\" \"" + exe + "\" \"" + inFile + "\" \"" + nlev + "\" \"" + sensor + "\" \"" + ch + "\" \"" + coeff + "\" \"" + 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
    if (ret == -1 || WEXITSTATUS(ret) != 0) {
        std::ifstream in(logFile.c_str());
        std::string line;

        if (WEXITSTATUS(ret) == 255) {
            setError(0, "RttovRun-> Warnings were generated during RTTOV run!");
        }
        else if (WEXITSTATUS(ret) == 1) {
            setError(1, "RttovRun-> Failed to perform RTTOV run!");
            runFailed = true;
        }
        else if (WEXITSTATUS(ret) > 1) {
            setError(1, "RttovRun-> RTTOV run failed with exit code: %d !", WEXITSTATUS(ret));
            runFailed = true;
        }
    }

    // Log locations are always printed!!

    if (runFailed) {
        marslog(LOG_EROR, "Log files are available at:");
        marslog(LOG_EROR, "---------------------------");
        marslog(LOG_EROR, " (STDOUT)  %s", logFile.c_str());
        std::string msg = tmpPath + "/fort.20";
        marslog(LOG_EROR, " (fort.20) %s", msg.c_str());

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

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

    /*if(!userResFile.empty())
    {
        const char *dn=dirname(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())
        {
            marslog(LOG_EROR,"");
            marslog(LOG_EROR,"Could not copy ouput file to target location!");
                marslog(LOG_EROR,"This command:");
            marslog(LOG_EROR,"   %s",cmd.c_str());
            marslog(LOG_EROR,"failed with this error:");
            marslog(LOG_EROR,"   %s",errStream.str().c_str());
            setError(13);
        }
    }*/

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

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

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


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

    RttovRun rttovRun;

    theApp.run();
}
