#include "environment.h"
#include "plain.h"

#include <saas/util/external/dc.h>

#define ENVIRONMENT_FILE_CONTENT_GENERATOR_TYPE "environment"

namespace NRTYDeploy {

    TEnvironmentFileContentGenerator::TEnvironmentFileContentGenerator()
    {}

    TEnvironmentFileContentGenerator::TEnvironmentFileContentGenerator(const TFsPath& path, const ICommonData& data, i64 version)
        : Slave(new TPlainFileContentGenerator(path, data, version))
    {}

    bool TEnvironmentFileContentGenerator::GetContent(TString& result, const ICommonData& common, const TContext& context) const {
        if (!Slave->GetContent(result, common, context))
            return false;

        result += "\n"
            "CTYPE=" + context.SlotInfo.CType    + "\n"
            "SERVICE_TYPE=" + context.SlotInfo.ServiceType + "\n"
            "SERVICE=" + context.SlotInfo.Service + "\n"
            "SLOT=" + context.SlotInfo.Slot + "\n"
            "SHARD_MIN=" + ToString(context.SlotInfo.ShardMin) + "\n"
            "SHARD_MAX=" + ToString(context.SlotInfo.ShardMax) + "\n"
            ;

        NRTYCluster::TSlotData slotData;
        if (NRTYCluster::TSlotData::Parse(context.SlotInfo.Slot, slotData)) {
            TString dc = slotData.GetDC();
            TString alias = slotData.GetDCAlias();
            if (!NSlotNameUtil::IsNormalDC(dc) && NSlotNameUtil::IsNormalDC(context.SlotInfo.DC)) {
                dc = context.SlotInfo.DC;
                TDatacenterUtil::Instance().GetDatacenterAlias(dc, alias);
            }
            result += "LOCATION=" + alias + "\n";
            result += "DATACENTER=" + dc + "\n";
        }

        return true;
    }

    TString TEnvironmentFileContentGenerator::GetType() const {
        return ENVIRONMENT_FILE_CONTENT_GENERATOR_TYPE;
    }

    void TEnvironmentFileContentGenerator::DoDeserialize(const NJson::TJsonValue& json) {
        TFileContentGenerator::DoDeserialize(json);
        Slave.Reset(Deserialize(json["slave"]));
    }

    void TEnvironmentFileContentGenerator::Serialize(NJson::TJsonValue& json) const {
        TFileContentGenerator::Serialize(json);
        Slave->Serialize(json["slave"]);
    }

    TString TEnvironmentFileContentGenerator::GetRename(const TContext& context) const {
        return Slave->GetRename(context);
    }

    void TEnvironmentFileContentGenerator::SetLastVersion() {
        Slave->SetLastVersion();
    }

    TEnvironmentFileContentGenerator::TFactory::TRegistrator<TEnvironmentFileContentGenerator> TEnvironmentFileContentGenerator::Registrar(ENVIRONMENT_FILE_CONTENT_GENERATOR_TYPE);
}
