#include "script.h"

#include <saas/library/http_utils/http_utils.h>

namespace NRTYDeploy {

    bool TScriptFetchFmlFormula::Process(IDeployInfoRequest& request) {
        const TCgiParameters& cgi = request.GetRD().CgiParam;
        const TString& from = cgi.Get("fml_id");
        const TString& to = cgi.Get("target_name");
        const TString& path = cgi.Get("path");

        if (to.empty()) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "Missing target name" << Endl;
            return true;
        }

        if (path.empty()) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "Missing path" << Endl;
            return true;
        }

        ui64 fmlId;
        if (!TryFromString<ui64>(from, fmlId)) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "Non-integer fml id: " << Endl;
            return true;
        }

        if (!request.GetCommonData().GetStorage().ExistsNode(path)) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "incorrect path: " << path << Endl;
            return true;
        }

        const TString targetPath(TString::Join(path, '/', to));
        if (request.GetCommonData().GetStorage().ExistsNode(targetPath)) {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "Node already exisis: " << targetPath << Endl;
            return true;
        }

        const TString fmlPath(TString::Join("/download/computed/formula?id=", from, "&file=matrixnet.info"));
        TStringStream sstr;
        try {
            NSaas::DoHttpGetRequest("https://fml.yandex-team.ru", 443, fmlPath, &sstr);
        } catch(const yexception& e) {
            request.Output() << "HTTP/1.1 500 \r\n\r\n";
            request.Output() << "Failed to fetch formula: " << e.what() << Endl;
            return true;
        }

        if (!request.GetCommonData().GetStorage().SetValue(targetPath, sstr.Str())) {
            request.Output() << "HTTP/1.1 500 \r\n\r\n";
            request.Output() << "Failed to save formula" << Endl;
            return true;
        }

        request.Output() << "HTTP/1.1 200 \r\n\r\n";
        request.Output() << "OK";
        return true;
    }

    IScript::TFactory::TRegistrator<TScriptFetchFmlFormula> TScriptFetchFmlFormula::Registrator("fetch_fml_formula");
}
