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

namespace core {
   
   Thread::Thread(EPoll &ePoll) : 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(Session *session) {   
      session->out << "|" << getThreadId(); 
      session->out << "|" << getStatus();
      session->out << "|" << getCount();       
   }
   
   
   void Thread::run() {
      
      threadId = syscall(SYS_gettid);
      
      Log(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;   
	       ePoll.eventReceived(events[ix]);            
	    }            
	 }      
      }
      
   }
   
}
