/***************************** 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 <unistd.h>
#include <pwd.h>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#include "fstream_mars_fix.h"

#include "Metview.h"
#include "MvService.h"

std::string ftmp;

// Globals
int ac;
char** av;

class MvCompress : public MvService
{
public:
    MvCompress(const char* name) :
        MvService(name) {}
    void serve(MvRequest&, MvRequest&) override;
};

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

    std::vector<std::string> vals;
    if (!in.getValue("ITEMS", vals))
        return;

    std::string method;
    if (const char* ch = in("PARAM")) {
        auto id = std::string(ch);
        std::vector<std::string> methods = {"tar", "tgz", "tbz", "tz", "zip", "gz", "bz2", "z"};
        if (std::find(methods.begin(), methods.end(), id) == methods.end()) {
            return;
        }
        method = id;
    }
    else {
        return;
    }

    // Dump file name + tar file name
    std::string fLog(marstmp());

    // Compress command
    std::string cmd = std::string(getenv("METVIEW_BIN")) + "/mv_compress ";

    cmd += " -m \"" + method + "\" -l \"" + fLog + "\" ";
    for (auto& val : vals) {
        cmd += "\"" + val + "\" ";
    }
    cmd += " 2>&1";

    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) {
        std::ifstream inLog(fLog.c_str());
        std::string line;
        std::string msg;
        std::string detailed;
        std::string st;

        if (WEXITSTATUS(ret) == 255) {
            msg = "MvCompress-> Some of the icons could not be archived!";
            st = "WARNING";
            setError(0, msg.c_str());
            // marslog(LOG_WARN,"%s",msg.c_str());
            while (getline(inLog, line)) {
                // marslog(LOG_WARN,"%s",line.c_str());
                detailed += line + "\n";
            }
            inLog.close();
        }
        else {
            st = "ERROR";
            if (WEXITSTATUS(ret) == 1) {
                msg = "MvCompress-> Failed to archive the selected icons!";
            }
            else {
                std::stringstream ss;
                ss << "MvCompress-> Icon archiving failed with exit code: " << WEXITSTATUS(ret) << "!";
                msg = ss.str();
            }

            setError(1, msg.c_str());
            // marslog(LOG_EROR,"%s",msg.c_str());
            while (getline(inLog, line)) {
                // marslog(LOG_EROR,"%s",line.c_str());
                detailed += line + "\n";
            }
            inLog.close();
        }

        out = MvRequest("MESSAGE");
        out("STATUS") = st.c_str();
        out("TEXT") = msg.c_str();
        out("DETAILED") = detailed.c_str();

        if (st == "ERROR") {
            setError(1, detailed.c_str());
            return;
        }
    }
}

int main(int argc, char** argv)
{
    ac = argc;
    av = argv;

    MvApplication theApp(argc, argv, "MvCompress");

    MvCompress arch("ARCHIVE");
    MvCompress cmp("COMPRESS");

    theApp.run();
}
