// This file is generated by TypeBuilder_cpp.template.

// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/devtools/protocol/web_mcp.h"

#include "content/browser/devtools/protocol/protocol.h"

#include "third_party/inspector_protocol/crdtp/cbor.h"
#include "third_party/inspector_protocol/crdtp/find_by_first.h"
#include "third_party/inspector_protocol/crdtp/span.h"

namespace content {
namespace protocol {
namespace WebMCP {

using crdtp::DeserializerState;
using crdtp::FallthroughCallback;
using crdtp::ProtocolTypeTraits;

// ------------- Enum values from types.

const char Metainfo::domainName[] = "WebMCP";
const char Metainfo::commandPrefix[] = "WebMCP.";
const char Metainfo::version[] = "1.3";

CRDTP_BEGIN_DESERIALIZER(Annotation)
    CRDTP_DESERIALIZE_FIELD_OPT("autosubmit", m_autosubmit),
    CRDTP_DESERIALIZE_FIELD_OPT("consequential", m_consequential),
    CRDTP_DESERIALIZE_FIELD_OPT("readOnly", m_readOnly),
    CRDTP_DESERIALIZE_FIELD_OPT("untrustedContent", m_untrustedContent),
CRDTP_END_DESERIALIZER()

CRDTP_BEGIN_SERIALIZER(Annotation)
    CRDTP_SERIALIZE_FIELD("readOnly", m_readOnly);
    CRDTP_SERIALIZE_FIELD("untrustedContent", m_untrustedContent);
    CRDTP_SERIALIZE_FIELD("consequential", m_consequential);
    CRDTP_SERIALIZE_FIELD("autosubmit", m_autosubmit);
CRDTP_END_SERIALIZER();



CRDTP_BEGIN_DESERIALIZER(Tool)
    CRDTP_DESERIALIZE_FIELD_OPT("annotations", m_annotations),
    CRDTP_DESERIALIZE_FIELD_OPT("backendNodeId", m_backendNodeId),
    CRDTP_DESERIALIZE_FIELD("description", m_description),
    CRDTP_DESERIALIZE_FIELD("frameId", m_frameId),
    CRDTP_DESERIALIZE_FIELD_OPT("inputSchema", m_inputSchema),
    CRDTP_DESERIALIZE_FIELD("name", m_name),
    CRDTP_DESERIALIZE_FIELD_OPT("stackTrace", m_stackTrace),
CRDTP_END_DESERIALIZER()

CRDTP_BEGIN_SERIALIZER(Tool)
    CRDTP_SERIALIZE_FIELD("name", m_name);
    CRDTP_SERIALIZE_FIELD("description", m_description);
    CRDTP_SERIALIZE_FIELD("inputSchema", m_inputSchema);
    CRDTP_SERIALIZE_FIELD("annotations", m_annotations);
    CRDTP_SERIALIZE_FIELD("frameId", m_frameId);
    CRDTP_SERIALIZE_FIELD("backendNodeId", m_backendNodeId);
    CRDTP_SERIALIZE_FIELD("stackTrace", m_stackTrace);
CRDTP_END_SERIALIZER();


CRDTP_BEGIN_DESERIALIZER(RemovedTool)
    CRDTP_DESERIALIZE_FIELD("frameId", m_frameId),
    CRDTP_DESERIALIZE_FIELD("name", m_name),
CRDTP_END_DESERIALIZER()

CRDTP_BEGIN_SERIALIZER(RemovedTool)
    CRDTP_SERIALIZE_FIELD("name", m_name);
    CRDTP_SERIALIZE_FIELD("frameId", m_frameId);
CRDTP_END_SERIALIZER();


// ------------- Enum values from params.


// ------------- Frontend notifications.

void Frontend::ToolsAdded(std::unique_ptr<protocol::Array<protocol::WebMCP::Tool>> tools)
{
    if (!frontend_channel_)
        return;
    crdtp::ObjectSerializer serializer;
    serializer.AddField(crdtp::MakeSpan("tools"), tools);
    frontend_channel_->SendProtocolNotification(crdtp::CreateNotification("WebMCP.toolsAdded", serializer.Finish()));
}

void Frontend::ToolsRemoved(std::unique_ptr<protocol::Array<protocol::WebMCP::RemovedTool>> tools)
{
    if (!frontend_channel_)
        return;
    crdtp::ObjectSerializer serializer;
    serializer.AddField(crdtp::MakeSpan("tools"), tools);
    frontend_channel_->SendProtocolNotification(crdtp::CreateNotification("WebMCP.toolsRemoved", serializer.Finish()));
}

void Frontend::ToolInvoked(const String& toolName, const String& frameId, const String& invocationId, const String& input)
{
    if (!frontend_channel_)
        return;
    crdtp::ObjectSerializer serializer;
    serializer.AddField(crdtp::MakeSpan("toolName"), toolName);
    serializer.AddField(crdtp::MakeSpan("frameId"), frameId);
    serializer.AddField(crdtp::MakeSpan("invocationId"), invocationId);
    serializer.AddField(crdtp::MakeSpan("input"), input);
    frontend_channel_->SendProtocolNotification(crdtp::CreateNotification("WebMCP.toolInvoked", serializer.Finish()));
}

void Frontend::ToolResponded(const String& invocationId, const String& status, std::unique_ptr<protocol::Value> output, std::optional<String> errorText, std::unique_ptr<protocol::Runtime::RemoteObject> exception)
{
    if (!frontend_channel_)
        return;
    crdtp::ObjectSerializer serializer;
    serializer.AddField(crdtp::MakeSpan("invocationId"), invocationId);
    serializer.AddField(crdtp::MakeSpan("status"), status);
    serializer.AddField(crdtp::MakeSpan("output"), output);
    serializer.AddField(crdtp::MakeSpan("errorText"), errorText);
    serializer.AddField(crdtp::MakeSpan("exception"), exception);
    frontend_channel_->SendProtocolNotification(crdtp::CreateNotification("WebMCP.toolResponded", serializer.Finish()));
}

void Frontend::flush()
{
    frontend_channel_->FlushProtocolNotifications();
}

void Frontend::sendRawNotification(std::unique_ptr<Serializable> notification)
{
    frontend_channel_->SendProtocolNotification(std::move(notification));
}

// --------------------- Dispatcher.

class DomainDispatcherImpl : public protocol::DomainDispatcher {
public:
    DomainDispatcherImpl(FrontendChannel* frontendChannel, Backend* backend)
        : DomainDispatcher(frontendChannel)
        , m_backend(backend) {}
    ~DomainDispatcherImpl() override { }

    using CallHandler = void (DomainDispatcherImpl::*)(crdtp::Dispatchable& dispatchable);

    bool Dispatch(crdtp::span<uint8_t> command_name, crdtp::Dispatchable& dispatchable) override;

    void enable(crdtp::Dispatchable& dispatchable);
    void disable(crdtp::Dispatchable& dispatchable);
    void invokeTool(crdtp::Dispatchable& dispatchable);
    void cancelInvocation(crdtp::Dispatchable& dispatchable);
 protected:
    Backend* m_backend;
};

namespace {
// This helper method with a static map of command methods (instance methods
// of DomainDispatcherImpl declared just above) by their name is used immediately below,
// in the DomainDispatcherImpl::Dispatch method.
DomainDispatcherImpl::CallHandler CommandByName(crdtp::span<uint8_t> command_name) {
  static auto* commands = [](){
    auto* commands = new std::vector<std::pair<crdtp::span<uint8_t>,
                              DomainDispatcherImpl::CallHandler>>{
    {
          crdtp::SpanFrom("cancelInvocation"),
          &DomainDispatcherImpl::cancelInvocation
    },
    {
          crdtp::SpanFrom("disable"),
          &DomainDispatcherImpl::disable
    },
    {
          crdtp::SpanFrom("enable"),
          &DomainDispatcherImpl::enable
    },
    {
          crdtp::SpanFrom("invokeTool"),
          &DomainDispatcherImpl::invokeTool
    },
    };
    return commands;
  }();
  return crdtp::FindByFirst<DomainDispatcherImpl::CallHandler>(*commands, command_name, nullptr);
}
}  // namespace

bool DomainDispatcherImpl::Dispatch(crdtp::span<uint8_t> command_name, crdtp::Dispatchable& dispatchable) {
  CallHandler handler = CommandByName(command_name);
  if (!handler) return false;

  (this->*handler)(dispatchable);
  return true;
}


namespace {


}  // namespace

void DomainDispatcherImpl::enable(crdtp::Dispatchable& dispatchable)
{
    // Prepare input parameters.

    std::unique_ptr<DomainDispatcher::WeakPtr> weak = weakPtr();
    DispatchResponse response = m_backend->Enable();
    if (response.IsFallThrough()) {
        dispatchable.DispatchFallThrough(response.Message());
        return;
    }
    if (weak->get())
        weak->get()->sendResponse(dispatchable.CallId(), response);
    return;
}

namespace {


}  // namespace

void DomainDispatcherImpl::disable(crdtp::Dispatchable& dispatchable)
{
    // Prepare input parameters.

    std::unique_ptr<DomainDispatcher::WeakPtr> weak = weakPtr();
    DispatchResponse response = m_backend->Disable();
    if (response.IsFallThrough()) {
        dispatchable.DispatchFallThrough(response.Message());
        return;
    }
    if (weak->get())
        weak->get()->sendResponse(dispatchable.CallId(), response);
    return;
}

class InvokeToolCallbackImpl : public Backend::InvokeToolCallback, public DomainDispatcher::Callback {
public:
    InvokeToolCallbackImpl(std::unique_ptr<DomainDispatcher::WeakPtr> backendImpl, crdtp::Dispatchable& dispatchable)
        : DomainDispatcher::Callback(std::move(backendImpl), dispatchable, crdtp::SpanFrom("WebMCP.invokeTool")) { }

    void sendSuccess(const String& invocationId) override
    {
        crdtp::ObjectSerializer serializer;
        serializer.AddField(crdtp::MakeSpan("invocationId"), invocationId);
        sendIfActive(serializer.Finish(), DispatchResponse::Success());
    }

    void fallThrough() override
    {
        fallThroughIfActive();
    }

    void sendFailure(const DispatchResponse& response) override
    {
        DCHECK(response.IsError());
        sendIfActive(nullptr, response);
    }
};

namespace {

struct invokeToolParams : public crdtp::DeserializableProtocolObject<invokeToolParams> {
    String frameId;
    String toolName;
    std::unique_ptr<protocol::DictionaryValue> input;
    DECLARE_DESERIALIZATION_SUPPORT();
};

CRDTP_BEGIN_DESERIALIZER(invokeToolParams)
    CRDTP_DESERIALIZE_FIELD("frameId", frameId),
    CRDTP_DESERIALIZE_FIELD("input", input),
    CRDTP_DESERIALIZE_FIELD("toolName", toolName),
CRDTP_END_DESERIALIZER()

}  // namespace

void DomainDispatcherImpl::invokeTool(crdtp::Dispatchable& dispatchable)
{
    // Prepare input parameters.
    auto deserializer = crdtp::DeferredMessage::FromSpan(dispatchable.Params())->MakeDeserializer();
    invokeToolParams params;
    if (!invokeToolParams::Deserialize(&deserializer, &params)) {
      ReportInvalidParams(dispatchable, deserializer);
      return;
    }

    m_backend->InvokeTool(params.frameId, params.toolName, std::move(params.input), std::make_unique<InvokeToolCallbackImpl>(weakPtr(), dispatchable));
}

namespace {

struct cancelInvocationParams : public crdtp::DeserializableProtocolObject<cancelInvocationParams> {
    String invocationId;
    DECLARE_DESERIALIZATION_SUPPORT();
};

CRDTP_BEGIN_DESERIALIZER(cancelInvocationParams)
    CRDTP_DESERIALIZE_FIELD("invocationId", invocationId),
CRDTP_END_DESERIALIZER()

}  // namespace

void DomainDispatcherImpl::cancelInvocation(crdtp::Dispatchable& dispatchable)
{
    // Prepare input parameters.
    auto deserializer = crdtp::DeferredMessage::FromSpan(dispatchable.Params())->MakeDeserializer();
    cancelInvocationParams params;
    if (!cancelInvocationParams::Deserialize(&deserializer, &params)) {
      ReportInvalidParams(dispatchable, deserializer);
      return;
    }

    std::unique_ptr<DomainDispatcher::WeakPtr> weak = weakPtr();
    DispatchResponse response = m_backend->CancelInvocation(params.invocationId);
    if (response.IsFallThrough()) {
        dispatchable.DispatchFallThrough(response.Message());
        return;
    }
    if (weak->get())
        weak->get()->sendResponse(dispatchable.CallId(), response);
    return;
}

namespace {
// This helper method (with a static map of redirects) is used from Dispatcher::wire
// immediately below.
const std::vector<std::pair<crdtp::span<uint8_t>, crdtp::span<uint8_t>>>& SortedRedirects() {
  static auto* redirects = [](){
    auto* redirects = new std::vector<std::pair<crdtp::span<uint8_t>, crdtp::span<uint8_t>>>{
    };
    return redirects;
  }();
  return *redirects;
}
}  // namespace

// static
void Dispatcher::wire(UberDispatcher* uber, Backend* backend)
{
    auto dispatcher = std::make_unique<DomainDispatcherImpl>(uber->channel(), backend);
    uber->WireBackend(crdtp::SpanFrom("WebMCP"), SortedRedirects(), std::move(dispatcher));
}

} // WebMCP
} // namespace content
} // namespace protocol
