#include "HTTPActionList.h"
#include "Log.h"
#include "HTTPParameters.h"
#include "FlowAction.h"
#include "Exception.h"

namespace http {

   bool HTTPActionList::processRequest(HTTPParameters &p) {

      p.httpRequest.response.setProtocol(p.httpRequest.request.getProtocol());
      coreutils::ZString uri = p.httpRequest.request.getURI();
      if(!uri.ifNext("/"))
         throw coreutils::Exception("Expecting a /.");

      coreutils::Log(coreutils::LOG_DEBUG_1) << "Requesting action '" << uri << "'.";

      try {
         return actions.at(uri)->action(p);
      }
      catch(...) {
         throw coreutils::Exception("Requested resource not found.");
      }

   }

   coreutils::ZString HTTPActionList::addAction(FlowAction *action) {
      coreutils::Log(coreutils::LOG_DEBUG_1) << "Adding flow action to list..." << action->getId();

      for(auto [key, actionItem] : actions) {
         coreutils::Log(coreutils::LOG_DEBUG_2) << "before: " << key;
      }

      coreutils::ZString name(action->getId());
      coreutils::Log(coreutils::LOG_DEBUG_2) << "getid: " << name;
      auto ret = actions.insert(std::make_pair(name, action));

      if(ret.second == false) {
         coreutils::Log(coreutils::LOG_DEBUG_2) << "already exists" << action->getId();
      }

      for(auto [key, actionItem] : actions) {
         coreutils::Log(coreutils::LOG_DEBUG_2) << "after: " << key;
      }

      return action->getId();
   }

//   void HTTPActionList::remove(HTTPPage &page) {}

   void HTTPActionList::matchUri(coreutils::ZString &comparator, coreutils::ZString &uri) {
   }

}


