/***************************** 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 <fstream>
#include <iostream>
#include <sstream>
#include "fstream_mars_fix.h"

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

std::string ftmp;

// Globals
int ac;
char** av;

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

class MvCompress : public Base
{
public:
    MvCompress() :
        Base("COMPRESS") {}
    void serve(MvRequest&, MvRequest&);
};

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;

    const char* id = in("PARAM");
    if (!id)
        return;

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

    if (strcmp(id, "tar") == 0) {
        method = "tar";
    }
    else if (strcmp(id, "tgz") == 0) {
        method = "tgz";
    }
    else if (strcmp(id, "tbz") == 0) {
        method = "tbz";
    }
    else if (strcmp(id, "tzip") == 0) {
        method = "tzip";
    }
    else if (strcmp(id, "zip") == 0) {
        method = "zip";
    }
    else {
        return;
    }

    //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";

    //COUT << "command " << cmd << std::endl;

    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 cmp;

    theApp.run();
}
