#include <VWeb.h>

namespace VWeb {
std::optional<Ref<Response>>
MiddleWareHandler::HandlePre(Ref<Request> &request) {
  for (auto &[key, middleWare] : m_MiddleWares) {
    auto data = middleWare->PreHandle(*request);
    if (data.has_value())
      return data;
  }
  return {};
}
void MiddleWareHandler::HandlePost(Ref<Request> &request,
                                   Ref<Response> &response) {
  for (auto &[key, middleWare] : m_MiddleWares) {
    if (!middleWare->PostHandle(*request, *response)) {
      break;
    }
  }
}
void MiddleWareHandler::Shutdown(Ref<Request> &request,
                                 Ref<Response> &response) {
  for (auto &[key, middleWare] : m_MiddleWares) {
    middleWare->Shutdown(*request, *response);
  }
}
Ref<MiddleWare> MiddleWareHandler::GetById(const char *id) {
  return m_MiddleWares[id];
}
Ref<MiddleWare> MiddleWareHandler::SetById(const char *id,
                                           const Ref<MiddleWare> &middleWare) {
  m_MiddleWares[id] = middleWare;
  return middleWare;
}
void MiddleWareHandler::RemoveById(const char *id) {
  if (m_MiddleWares.contains(id))
    m_MiddleWares.erase(id);
}
} // namespace VWeb