#include "script.h"
#include <saas/deploy_manager/server/client/client.h>

#include <saas/deploy_manager/meta/cluster.h>
#include <saas/library/searchmap/searchmap.h>

namespace NRTYDeploy {

    bool TTransferServiceScript::Process(IDeployInfoRequest& request) {
        TString action = request.GetRD().CgiParam.Get("action");
        if (action == "copy_cluster") {
            TString ctypeFrom = request.GetRD().CgiParam.Get("ctype_from");
            TString ctypeTo = request.GetRD().CgiParam.Get("ctype_to");
            TString service = request.GetRD().CgiParam.Get("service");
            if (!service || !ctypeFrom || !ctypeTo) {
                request.Output() << "HTTP/1.1 400 \r\n\r\n";
                request.Output() << "Empty service, ctype_from or ctype_to";
                return false;
            }

            const NSaas::TClusterConst* clusterPtrIn = NSaas::TClusterLocker::DefineConst(request, ctypeFrom);
            if (!clusterPtrIn) {
                ythrow yexception() << "Incorrect cluster info for " << ctypeFrom;
            }
            const NSearchMapParser::TSearchMap& smFrom = clusterPtrIn->RTYSearchMap();
            const NSearchMapParser::TSearchMapService* serviceMap = smFrom.GetService(service);

            NSaas::TClusterLocker clusterPtr = NSaas::TClusterLocker::DefineMutable(request, ctypeTo);
            if (!clusterPtr) {
                request.Output() << "HTTP/1.1 500 \r\n\r\n";
                request.Output() << "Resource " << "/common/" << ctypeTo << "/cluster.meta is not available for modification";
                return false;
            }
            SetData(clusterPtr.GetContent(), "");

            clusterPtr->AddRTYService(*serviceMap);

            TString error;
            if (!clusterPtr->Validate(error)) {
                DEBUG_LOG << "Can't store cluster meta: " << error << Endl;
                request.Output() << "HTTP/1.1 400 \r\n\r\n";
                request.Output() << "Incorrect new cluster: " << error;
                return false;
            }
            SetData("", clusterPtr.GetContent());
            if (!clusterPtr.Save()) {
                request.Output() << "HTTP/1.1 500 \r\n\r\n";
                request.Output() << "Incorrect storage structure";
                return false;
            }

            request.Output() << "HTTP/1.1 200 Ok\r\n\r\n";
            return true;
        } else {
            request.Output() << "HTTP/1.1 400 \r\n\r\n";
            request.Output() << "Unknown action: '" << action << "'\r\n";
        }
        return true;
    }

    IScript::TFactory::TRegistrator<TTransferServiceScript> TTransferServiceScript::Registrator("transfer_service");
}
