#include "allowed_fp_mappings.h"
#include <util/string/split.h>

namespace {
static constexpr char DerictivesDelimeter = ' ';
static constexpr char PairDelimiter = '>';
}

namespace NRTYServer {
    bool TAllowedFingerprintMappings::IsCompitable(TStringBuf queryFingerPrint, TStringBuf baseFingerPrint) const {
        Y_ENSURE(!ParseErrorString, "AllowedFingerprintMappings parsing error: " << *ParseErrorString);
        if (queryFingerPrint == baseFingerPrint) {
            return true;
        }
        if (auto ptr = Data.FindPtr(queryFingerPrint)) {
            return ptr->contains(baseFingerPrint);
        }
        return false;
    }

    void TAllowedFingerprintMappings::ParseFromConfigStr(TStringBuf in) {
        try {
            TVector<TStringBuf> parts;
            StringSplitter(in).Split(DerictivesDelimeter).AddTo(&parts);
            for (TStringBuf p : parts) {
                if (p.empty()) {
                    continue;
                }
                TStringBuf from, to;

                Split(p, PairDelimiter, from, to);
                Data[TString{from}].insert(TString{to});
            }
        } catch (yexception& e) {
            Data.clear();
            ParseErrorString = e.what();
        }
    }

    void TAllowedFingerprintMappings::DoToString(IOutputStream& so) const {
        for (auto& pair : Data) {
            for (auto& to : pair.second) {
                so << pair.first << PairDelimiter << to << DerictivesDelimeter;
            }
        }
    }
}
