#include "HTTPPageList.h"
#include "Log.h"
#include "Exception.h"
#include <utility>

namespace http {

   bool HTTPPageList::processRequest(HTTPParameters &p) {

      p.httpRequest.response.setProtocol(p.httpRequest.request.getProtocol());
      coreutils::ZString uri = p.httpRequest.request.getURI();

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

      for (auto const& [key, val] : pages) {
         p.httpRequest.uriValues.clear();
         uri.reset();
         coreutils::ZString compare(key.c_str());
         int match = compare.ifEqualsCount(uri);
         if((match > 0) && (!uri.eod())) {
            if(compare.ifNext("{")) {
               coreutils::ZString varName = compare.getTokenExclude("}");
               if(compare.ifNext("}")) {
                  if(compare.eod()) {
                     coreutils::ZString value = uri.getTokenExclude(" ");
                     p.httpRequest.uriValues[varName] = value;
                  }
               } else
                 throw coreutils::Exception("Syntax error in entrypoint data.");
            }
         }
         if((match > 0) && uri.eod()) {
            return val->page(p);
         }
      }
      throw coreutils::Exception("Requested resource not found.");
   }

   void HTTPPageList::add(HTTPPage &page, std::string name) {
      pages.insert(std::make_pair(name, &page));
   }

   void HTTPPageList::remove(HTTPPage &page) {}

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

}


