#include "my_process.h"
#include "util.h"

namespace My_Process { 
#define debug false
struct Utils::Result<string> My_Process_call::call(string cmd) {
    this->i_error_old = this->i_error;
    struct Utils::Result<string> obj_result;
    string response = Utils::call(cmd);
    obj_result.response = response;
    if ((response.find("(null)") == std::string::npos) && (response.length() != 0 )) {
        if (response.find("=") != std::string::npos) {
            if (response.find("\n") != std::string::npos) {
                response = response.substr(response.find("=")+1,response.length());
                response = response.substr(0,response.find("\n"));
                obj_result.response = response;
                obj_result.error = 0;
            }
            else {
                obj_result.error = 1;
                this->i_error += 1;
                this->log_mess_error(cmd);
            }
        }
        else {
            obj_result.error = 2;
            this->i_error += 1;
            str_cmd_error = cmd;
            this->log_mess_error(cmd);
        }
    }
    else {
        obj_result.error = 3;
        this->i_error += 1;
        str_cmd_error = cmd;
        this->log_mess_error(cmd);
    }
    return obj_result;
}

int My_Process::get_count_error() {
    return this->i_error;
}

void My_Process::set_back_count_error() {
    this->i_error = this->i_error_old;
}

void My_Process_system::call(string cmd, string thread_str = "") {
    string cmd_new = cmd + " " + thread_str;
    int response_cmd = system(cmd_new.c_str());
    if (response_cmd != 0) {
        this->i_error += 1;
    }
}

void My_Process::set_count_error(int count_error) {
    this->i_error = count_error;
    this->str_cmd_error = "";
}

void My_Process::log_mess_error(string) {
}

string My_Process::get_cmd_error() {
    return this->str_cmd_error;
}
string My_Process_call::call_all_sections(string cmd) {
    char buffer[PATH_MAX] = {0};
    std::string result = "";
    FILE* pipe = popen(cmd.c_str(), "r");
    if (!pipe) throw std::runtime_error("popen() failed!");
    try {
        while (fgets(buffer, sizeof buffer, pipe) != NULL) {
            result += buffer;
        }
    } catch (...) {
        pclose(pipe);
        throw;
    }
    pclose(pipe);
    return result;
}
}