//------------------------------------------------------------------------------
/*
    This file is part of clio: https://github.com/XRPLF/clio
    Copyright (c) 2023, the clio developers.

    Permission to use, copy, modify, and distribute this software for any
    purpose with or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL,  DIRECT,  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include "rpc/handlers/AccountOffers.hpp"

#include "rpc/Errors.hpp"
#include "rpc/JS.hpp"
#include "rpc/RPCHelpers.hpp"
#include "rpc/common/Types.hpp"
#include "util/Assert.hpp"
#include "util/JsonUtils.hpp"

#include <boost/json/conversion.hpp>
#include <boost/json/value.hpp>
#include <boost/json/value_from.hpp>
#include <boost/json/value_to.hpp>
#include <xrpl/basics/strHex.h>
#include <xrpl/protocol/AccountID.h>
#include <xrpl/protocol/Indexes.h>
#include <xrpl/protocol/LedgerFormats.h>
#include <xrpl/protocol/LedgerHeader.h>
#include <xrpl/protocol/SField.h>
#include <xrpl/protocol/STAmount.h>
#include <xrpl/protocol/STLedgerEntry.h>
#include <xrpl/protocol/UintTypes.h>
#include <xrpl/protocol/jss.h>

#include <cstdint>
#include <string>
#include <vector>

namespace rpc {

void
AccountOffersHandler::addOffer(std::vector<Offer>& offers, ripple::SLE const& offerSle)
{
    auto offer = AccountOffersHandler::Offer();
    offer.takerPays = offerSle.getFieldAmount(ripple::sfTakerPays);
    offer.takerGets = offerSle.getFieldAmount(ripple::sfTakerGets);
    offer.seq = offerSle.getFieldU32(ripple::sfSequence);
    offer.flags = offerSle.getFieldU32(ripple::sfFlags);

    auto const quality = getQuality(offerSle.getFieldH256(ripple::sfBookDirectory));
    auto const rate = ripple::amountFromQuality(quality);
    offer.quality = rate.getText();

    if (offerSle.isFieldPresent(ripple::sfExpiration))
        offer.expiration = offerSle.getFieldU32(ripple::sfExpiration);

    offers.push_back(offer);
};

AccountOffersHandler::Result
AccountOffersHandler::process(AccountOffersHandler::Input const& input, Context const& ctx) const
{
    auto const range = sharedPtrBackend_->fetchLedgerRange();
    ASSERT(range.has_value(), "AccountOffer's ledger range must be available");
    auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq(
        *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence
    );

    if (!expectedLgrInfo.has_value())
        return Error{expectedLgrInfo.error()};

    auto const& lgrInfo = expectedLgrInfo.value();
    auto const accountID = accountFromStringStrict(input.account);
    auto const accountLedgerObject =
        sharedPtrBackend_->fetchLedgerObject(ripple::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield);

    if (!accountLedgerObject)
        return Error{Status{RippledError::rpcACT_NOT_FOUND, "accountNotFound"}};

    Output response;
    response.account = ripple::to_string(*accountID);
    response.ledgerHash = ripple::strHex(lgrInfo.hash);
    response.ledgerIndex = lgrInfo.seq;

    auto const addToResponse = [&](ripple::SLE const sle) {
        if (sle.getType() == ripple::ltOFFER)
            addOffer(response.offers, sle);

        return true;
    };

    auto const expectedNext = traverseOwnedNodes(
        *sharedPtrBackend_, *accountID, lgrInfo.seq, input.limit, input.marker, ctx.yield, addToResponse
    );

    if (!expectedNext.has_value())
        return Error{expectedNext.error()};

    auto const nextMarker = expectedNext.value();

    if (nextMarker.isNonZero())
        response.marker = nextMarker.toString();

    return response;
}

void
tag_invoke(boost::json::value_from_tag, boost::json::value& jv, AccountOffersHandler::Output const& output)
{
    jv = {
        {JS(ledger_hash), output.ledgerHash},
        {JS(ledger_index), output.ledgerIndex},
        {JS(validated), output.validated},
        {JS(account), output.account},
        {JS(offers), boost::json::value_from(output.offers)},
    };

    if (output.marker)
        jv.as_object()[JS(marker)] = *output.marker;
}

void
tag_invoke(boost::json::value_from_tag, boost::json::value& jv, AccountOffersHandler::Offer const& offer)
{
    jv = {
        {JS(seq), offer.seq},
        {JS(flags), offer.flags},
        {JS(quality), offer.quality},
    };

    auto& jsonObject = jv.as_object();

    if (offer.expiration)
        jsonObject[JS(expiration)] = *offer.expiration;

    auto const convertAmount = [&](char const* field, ripple::STAmount const& amount) {
        if (amount.native()) {
            jsonObject[field] = amount.getText();
        } else {
            jsonObject[field] = {
                {JS(currency), ripple::to_string(amount.getCurrency())},
                {JS(issuer), ripple::to_string(amount.getIssuer())},
                {JS(value), amount.getText()},
            };
        }
    };

    convertAmount(JS(taker_pays), offer.takerPays);
    convertAmount(JS(taker_gets), offer.takerGets);
}

AccountOffersHandler::Input
tag_invoke(boost::json::value_to_tag<AccountOffersHandler::Input>, boost::json::value const& jv)
{
    auto input = AccountOffersHandler::Input{};
    auto const& jsonObject = jv.as_object();

    input.account = boost::json::value_to<std::string>(jsonObject.at(JS(account)));

    if (jsonObject.contains(JS(ledger_hash)))
        input.ledgerHash = boost::json::value_to<std::string>(jsonObject.at(JS(ledger_hash)));

    if (jsonObject.contains(JS(ledger_index))) {
        auto const expectedLedgerIndex = util::getLedgerIndex(jsonObject.at(JS(ledger_index)));
        if (expectedLedgerIndex.has_value())
            input.ledgerIndex = *expectedLedgerIndex;
    }

    if (jsonObject.contains(JS(limit)))
        input.limit = util::integralValueAs<uint32_t>(jsonObject.at(JS(limit)));

    if (jsonObject.contains(JS(marker)))
        input.marker = boost::json::value_to<std::string>(jsonObject.at(JS(marker)));

    return input;
}

}  // namespace rpc
