/*
    SPDX-FileCopyrightText: 2012 Joris Guisson <joris.guisson@gmail.com>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "getpeersrsp.h"
#include "dht.h"
#include <bcodec/bencoder.h>
#include <bcodec/bnode.h>
#include <util/error.h>
#include <util/functions.h>
#include <util/log.h>

using namespace bt;
using namespace Qt::Literals::StringLiterals;

namespace dht
{
GetPeersRsp::GetPeersRsp()
    : RPCMsg(QByteArray(), dht::GET_PEERS, dht::RSP_MSG, QByteArray())
{
}

GetPeersRsp::GetPeersRsp(const QByteArray &mtid, const Key &id, const QByteArray &token)
    : RPCMsg(mtid, dht::GET_PEERS, dht::RSP_MSG, id)
    , token(token)
{
}

GetPeersRsp::GetPeersRsp(const QByteArray &mtid, const Key &id, const DBItemList &values, const QByteArray &token)
    : RPCMsg(mtid, dht::GET_PEERS, dht::RSP_MSG, id)
    , token(token)
    , items(values)
{
}

GetPeersRsp::~GetPeersRsp()
{
}

void GetPeersRsp::apply(dht::DHT *dh_table)
{
    dh_table->response(*this);
}

void GetPeersRsp::print()
{
    Out(SYS_DHT | LOG_DEBUG) << u"RSP: %1 %2 : get_peers(%3)"_s.arg(mtid[0]).arg(id.toString(), nodes.size() > 0 ? u"nodes"_s : u"values"_s) << endl;
}

void GetPeersRsp::encode(QByteArray &arr) const
{
    BEncoder enc(std::make_unique<BEncoderBufferOutput>(arr));
    enc.beginDict();
    {
        enc.write(RSP);
        enc.beginDict();
        {
            enc.write("id", id);
            if (nodes.size() > 0) {
                enc.write("nodes", nodes);
            }

            if (nodes6.size() > 0) {
                enc.write("nodes6", nodes6);
            }

            enc.write("token", token);

            if (items.size() > 0) {
                enc.write("values");
                enc.beginList();
                DBItemList::const_iterator i = items.begin();
                while (i != items.end()) {
                    const DBItem &item = *i;
                    // Buffer large enough for a compact IPv6 address but we may also write a compact IPv4 address.
                    std::array<Uint8, 18> tmp;
                    const Uint32 b = item.pack(tmp.data());
                    enc.write(QByteArrayView{tmp}.first(b));
                    ++i;
                }
                enc.end();
            }
        }
        enc.end();
        enc.write(TID, mtid);
        enc.write(TYP, RSP);
    }
    enc.end();
}

void GetPeersRsp::parse(BDictNode *dict)
{
    dht::RPCMsg::parse(dict);
    BDictNode *args = dict->getDict(RSP);
    if (!args) {
        throw bt::Error(u"Invalid response, arguments missing"_s);
    }

    token = args->getByteArrayView("token").left(MAX_TOKEN_SIZE).toByteArray();

    BListNode *vals = args->getList("values");
    if (vals) {
        for (Uint32 i = 0; i < vals->getNumChildren(); i++) {
            const auto d = vals->getByteArrayView(i);
            if (d.length() == 6) { // IPv4
                const auto addr = net::Address::fromCompactIPv4(d);
                items.append(DBItem(addr));
            } else if (d.length() == 18) { // IPv6
                const auto addr = net::Address::fromCompactIPv6(d);
                items.append(DBItem(addr));
            }
        }
    }

    if (args->getValue("nodes") || args->getList("nodes6")) {
        const BValueNode *v = args->getValue("nodes");
        if (v) {
            nodes = v->data().toByteArray();
        }

        v = args->getValue("nodes6");
        if (v) {
            nodes6 = v->data().toByteArray();
        }
    }
}
}
