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

Copyright 2021 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 "mars.h"

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

#include "MvRequest.h"
#include "MvProtocol.h"
#include "MvService.h"

#include "MvApplication.h"
#include "MvException.h"
#include "MvMiscellaneous.h"
#include "MvScanFileType.h"
#include "Path.h"


class CommandArg
{
public:
    CommandArg(const std::string& param, const std::string& name, bool canBeEmpty) :
        param_(param), name_(name), canBeEmpty_(canBeEmpty) {}
    virtual std::string build(const MvRequest& req) = 0;

protected:
    std::string param_;
    std::string name_;
    bool canBeEmpty_{false};
    std::string value_;

    std::string buildIt()
    {
        if (!value_.empty()) {
            return "--" + name_ + " " + value_;
        }
        return {};
    }
};


class SingleCommandArg : public CommandArg
{
public:
    using CommandArg::CommandArg;

    std::string build(const MvRequest& req) override
    {
        std::string v;
        if (req.getValue(param_, v, canBeEmpty_)) {
            metview::toLower(v);
            value_ = v;
        }
        else {
            throw MvException("");
        }
        return buildIt();
    }
};


class ListCommandArg : public CommandArg
{
    std::string separator_{"/"};

public:
    using CommandArg::CommandArg;

    std::string build(const MvRequest& req) override
    {
        std::vector<std::string> vec;
        if (req.getValue(param_, vec, canBeEmpty_)) {
            for (auto v : vec) {
                if (!value_.empty()) {
                    value_ += separator_;
                }
                metview::toLower(v);
                value_ += v;
            }
        }
        else {
            throw MvException("");
        }
        return buildIt();
    }
};

class YesNoParam
{
public:
    YesNoParam(const std::string& param, const MvRequest& req) :
        param_(param)
    {
        if (req.getValue(param, value_, false)) {
            status_ = (value_ == "YES");
        }
        else {
            throw MvException("");
        }
    }
    const std::string& param() const { return param_; }
    const std::string& value() const { return value_; }
    bool status() const { return status_; }

protected:
    std::string param_;
    std::string value_;
    bool status_{false};
};

// =================================================
//
// Stvl
//
// =================================================

class Stvl : public MvService
{
public:
    using MvService::MvService;
    ~Stvl() = default;

private:
    void serve(MvRequest& in, MvRequest& out) override;
};


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

    try {
        MvRequest r = in.ExpandRequest("StvlDef", "StvlRules", EXPAND_DEFAULTS);
        r.print();

        std::vector<CommandArg*> cmdArgs = {
            new SingleCommandArg("PARAMETER", "parameter", false),
            new SingleCommandArg("PERIOD", "period", true),
            new ListCommandArg("DATES", "dates", false),
            new ListCommandArg("TIMES", "times", false),
            new ListCommandArg("STEPS", "steps", true),
            new SingleCommandArg("TABLE", "table", true),
            new SingleCommandArg("MCLASS", "mclass", true),
            new SingleCommandArg("STREAM", "stream", true),
            new SingleCommandArg("EXPVER", "expver", true),
            new SingleCommandArg("MTYPE", "mtype", true),
            new SingleCommandArg("ORIGIN", "origin", true),
            new SingleCommandArg("ANOFFSET", "anoffset", true),
            new ListCommandArg("COLUMNS", "columns", true),
            new ListCommandArg("SOURCES", "sources", true),
        };

        YesNoParam failOnError("FAIL_ON_ERROR", r);
        YesNoParam failOnEmpty("FAIL_ON_EMPTY_OUTPUT", r);

        // build the command arguments
        std::string scriptArgs;
        for (auto a : cmdArgs) {
            scriptArgs += " " + a->build(r);
        }

        scriptArgs += " --flattree";

        // find out the stvl script path
        std::string stvlScript = "mv_stvl";
        char* mvbin            = getenv("METVIEW_BIN");
        if (mvbin == nullptr) {
            throw MvException("No METVIEW_BIN env variable is defined. Cannot locate script " + stvlScript + "!");
        }
        else {
            stvlScript = std::string(mvbin) + "/" + stvlScript;
        }

        // create tmp dir for the output
        std::string tmpPath;
        std::string errTxt;
        if (!metview::createWorkDir("stvl", tmpPath, errTxt)) {
            throw MvException(errTxt.c_str());
        }

        // define log file
        std::string logFileName = "log.txt";
        std::string logFile     = Path(tmpPath).add(logFileName).str();
        int maxLogLineNum       = 1000;

        // define res file
        std::string resFileName = "res.gpt";

        // run the script
        std::string cmd = stvlScript + " \"" + tmpPath + "\" \"" +
                          logFileName + "\" \"" +
                          resFileName + "\" \"" +
                          scriptArgs + "\"";

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

        //If the script failed, read log file and write it into LOG_EROR
        if (ret == -1 || WEXITSTATUS(ret) != 0) {
            marslog(LOG_EROR, "Failed to perform STVL retrieval!");
            metview::writeFileToLogErr(logFile, maxLogLineNum);
            if (failOnError.status()) {
                throw MvException("Abort due to " + failOnError.param() + "=" +
                                  failOnError.value());
            }
            else {
                return;
            }
            //        } else {
            //            metview::writeFileToLogInfo(logFile, maxLogLineNum);
        }

        // -----------------------
        // handle output
        // -----------------------

        Path rp(tmpPath);
        rp = rp.add(resFileName);
        if (!rp.exists()) {
            if (failOnEmpty.status()) {
                throw MvException("No output generated! Abort due to " + failOnEmpty.param() + "=" +
                                  failOnEmpty.value());
            }
            else {
                marslog(LOG_EROR, "STVL: no ouput generated!");
            }
        }
        else if (rp.sizeInBytes() == 0) {
            if (failOnEmpty.status()) {
                throw MvException("Empty output generated! Abort due to " + failOnEmpty.param() + "=" +
                                  failOnEmpty.value());
            }
            else {
                marslog(LOG_EROR, "STVL: empty ouput generated!");
            }
        }
        else {
            std::string fType = ScanFileType(rp.str().c_str());
            if (fType == "GEOPOINTS" || fType == "GEOPOINTSET") {
                out         = MvRequest(fType.c_str());
                out("PATH") = rp.str().c_str();
            }
            else {
                if (failOnEmpty.status()) {
                    throw MvException("Invalid output generated! Abort due to " + failOnEmpty.param() + "=" +
                                      failOnEmpty.value());
                }
                else {
                    marslog(LOG_EROR, "STVL: invalid ouput generated!");
                }
            }
        }
    }
    catch (MvException& e) {
        std::string err = "STVL-> Failed! ";
        err += e.what();
        throw MvException(err.c_str());
    }

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


//--------------------------------------------------------


int main(int argc, char** argv)
{
    MvApplication theApp(argc, argv);
    Stvl p("STVL");

    theApp.run();
}
