#include "Subscription.h"
#include "TCPSession.h"
#include "Log.h"
#include <algorithm>

namespace core
{

   Subscription::Subscription(std::string id, std::string mode)
       : id(id), mode(mode), owner(NULL) {}

   Subscription::Subscription(std::string id, TCPSession &session, std::string mode)
       : id(id), mode(mode), owner(&session) {}

   Subscription::~Subscription()
   {
      std::stringstream out;
      out << "cancel:" << id << std::endl;
      for (auto subscriber : subscribers)
      {
         subscriber->write(out.str());
      }
   }

   int Subscription::subscribe(TCPSession &session)
   {
      onSubscribe(session);
      subscribers.push_back(&session);
      return 1;
   }

   int Subscription::unsubscribe(TCPSession &session)
   {
      for (auto subscriber = subscribers.begin(); subscriber < subscribers.end(); ++subscriber)
      {
         if (*subscriber == &session)
         {
            subscribers.erase(subscriber++);
            return 1;
         }
      }
      return 0;
   }

   int Subscription::process(coreutils::ZString &request, std::stringstream &out, TCPSession &session)
   {
      out << "event:" << request[1] << ":" << request[2] << std::endl;
      return 1;
   }

   int Subscription::event(std::stringstream &out)
   {
      for (auto subscriber = subscribers.begin(); subscriber < subscribers.end(); ++subscriber)
         (*subscriber)->write(out.str());
      return 1;
   }

   bool Subscription::ifSubscriber(TCPSession &session)
   {
      return (std::find(subscribers.begin(), subscribers.end(), &session) != subscribers.end());
   }

   int Subscription::onSubscribe(TCPSession &session)
   {
      return 0;
   }

}
