#include "Thread.h"
#include "EPoll.h"

namespace core {

   Thread::Thread(EPoll &ePoll) : ePoll(ePoll) {}
   Thread::Thread(EPoll &ePoll, ThreadScope *scope) : ePoll(ePoll) {}

   Thread::~Thread() {}

   void Thread::start() {
      _thread = new std::thread(&Thread::run, this);
   }

   void Thread::join() {
      _thread->join();
   }

   std::string Thread::getStatus() {
      return status;
   }

   pid_t Thread::getThreadId() {
      return threadId;
   }

   int Thread::getCount() {
      return count;
   }

   void Thread::output(std::stringstream &data) {
      data << "|" << getThreadId();
      data << "|" << getStatus();
      data << "|" << getCount();
   }

   void Thread::run() {

      threadId = syscall(SYS_gettid);

      coreutils::Log(coreutils::LOG_DEBUG_1) << "Thread started with thread id " << threadId << ".";

      count = 0;

      struct epoll_event events[50];

      while(1) {

	      if(ePoll.isStopping())
           break;

	      status = "WAITING";
	      int rc = epoll_wait(ePoll.getDescriptor(), events, 50, -1);
	      status = "RUNNING";

	      if(rc < 0) {
	      // TODO: Make log entry indicating status received and ignore for now.
	      } else if(rc == 0) {
	         break;
	      } else if(rc > 0) {
	         for(int ix = 0; ix < rc; ++ix) {
	            ++count;
	            if(((Socket *)events[ix].data.ptr)->eventReceived(events[ix], ++ePoll.eventId)) {
//                  coreutils::Log(coreutils::LOG_DEBUG_4) << "return true";
//		            ePoll.resetSocket((Socket *)events[ix].data.ptr);
	            } else {
                  ((Socket *)events[ix].data.ptr)->shutDown = true;
//                  coreutils::Log(coreutils::LOG_DEBUG_4) << "return false";
                  delete (Socket *)events[ix].data.ptr;
               }
            }
   	   }
      }
      coreutils::Log(coreutils::LOG_DEBUG_1) << "Thread ending with thread id " << threadId << ".";
   }

}
