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

 Copyright 2016 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 "MvCompressRun.h"
#include "MvException.h"
#include "MvExitStatus.h"
#include "MvMiscellaneous.h"
#include "MvTmpFile.h"

#include <cassert>
#include <fstream>
#include <iostream>

namespace metview {
namespace compress {


void MvCompressRun::enableMailMode(const std::string& compressFile, const std::string& dumpFile)
{
    mailMode_=true;
    compressFile_=compressFile;
    dumpFile_=dumpFile;
}

int MvCompressRun::run(MvRequest& in, MvRequest& out)
{
    in.print();

    try {
        std::vector<std::string> vals;
        if (!in.getValue("ITEMS", vals)) {
            throw MvException("ITEMS not defined");
        }

        std::string compressMethod;
        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()) {
                throw MvException("Unsupported output type=" + id);
            }
            compressMethod = id;
        }
        else {
            throw MvException("PARAM not defined");
        }

        MvTmpFile fLog;

        // Compress command
        std::string cmd = std::string(getenv("METVIEW_BIN")) + "/mv_compress ";
        if (mailMode_) {
            cmd += " -f \"" + compressFile_ + "\" -d \"" + dumpFile_ + "\" -m \"" + compressMethod + "\" -l \"" + fLog.path() + "\" ";
        } else {
            cmd += " -m \"" + compressMethod + "\" -l \"" + fLog.path() + "\" ";
        }

        for (auto& val : vals) {
            cmd += "\"" + val + "\" ";
        }
        cmd += " 2>&1";

        MvExitStatus ret(system(cmd.c_str()));

        // If the script failed read log file and
        // write it into LOG_EROR
        if (!ret.isSuccess()) {
            std::string msg;
            std::string detailed;
            std::string st;

            detailed = metview::textFileContents(fLog.path());
            if (ret.isWarning()) {
                msg = "Some of the icons could not be archived!";
                st = "WARNING";
            }
            else if (ret.isError()) {
                st = "ERROR";
                if (ret.exitCode() == 1) {
                    msg = "Failed to archive the selected icons!";
                }
                else {
                    msg = "Icon archiving failed with exit code: " + std::to_string(ret.exitCode());
                }
            } else {
                assert(0);
                throw MvException("MvExitStatus is in an invalid state!");
            }

            out = MvRequest("MESSAGE");
            out("STATUS") = st.c_str();
            out("TEXT") = msg.c_str();
            out("DETAILED") = detailed.c_str();
            for (auto v: vals) {
                out.addValue("FAILED_ITEMS", v.c_str());
            }

            if (st == "ERROR") {
                return 1;
            }
        }
    } catch (MvException(e)) {
        out = MvRequest("MESSAGE");
        out("STATUS") = "ERROR";
        out("TEXT") = e.what();
        return 1;
    }

    return 0;
}

}
}
