#include "INotify.h"
#include "Log.h"
#include "ZString.h"

namespace core {

   INotify::INotify(EPoll &ePoll) : Socket(ePoll, "INotify") {
      setDescriptor(inotify_init());
   }

   INotify::~INotify() {
      shutdown();
   }

   int INotify::addWatch(coreutils::ZString &watch) {
      return inotify_add_watch(getDescriptor(), watch.c_str(), IN_ALL_EVENTS);
   }

   void INotify::removeWatch(int wd) {
      inotify_rm_watch(getDescriptor(), wd);
   }

   void INotify::onDataReceived(coreutils::ZString &buffer) {
      const struct inotify_event *event;
      char *ptr;
      for (ptr = buffer.getData();
	   ptr < buffer.getData() + buffer.getLength();
	   ptr += sizeof(struct inotify_event) + event->len) {
	 event = (const struct inotify_event *) ptr;
	 coreutils::ZString name(event->name);

	 if(event->mask & IN_ACCESS)
	   inAccess(name);
	 if(event->mask & IN_ATTRIB)
	   inAttrib(std::string(event->name));
	 if(event->mask & IN_CLOSE_WRITE)
	   inCloseWrite(std::string(event->name));
	 if(event->mask & IN_CLOSE_NOWRITE)
	   inCloseNoWrite(std::string(event->name));
	 if(event->mask & IN_CREATE)
	   inCreate(name);
	 if(event->mask & IN_DELETE)
	   inDelete(std::string(event->name));
	 if(event->mask & IN_DELETE_SELF)
	   inDeleteSelf(std::string(event->name));
	 if(event->mask & IN_MODIFY)
	   inModify(std::string(event->name));
	 if(event->mask & IN_MOVE_SELF)
	   inMoveSelf(std::string(event->name));
	 if(event->mask & IN_MOVED_FROM)
	   inMovedFrom(std::string(event->name));
	 if(event->mask & IN_MOVED_TO)
	   inMovedTo(std::string(event->name));
	 if(event->mask & IN_OPEN)
	   inOpen(std::string(event->name));
      }
   }

}
