/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <stdio.h> 
#include <strings.h>

#include "MvQFileWatcher.h"

#include <QFileSystemWatcher>

MvQFileWatcher::MvQFileWatcher():
	file_(0),
	watcher_(0)
{
}

MvQFileWatcher::~MvQFileWatcher()
{
	stop();
}

void MvQFileWatcher::stop()
{
	if(file_)
	{
		if(watcher_)
		{
		  	delete watcher_;
			watcher_=0;
		}	
		  
		file_ = 0;
	}
}

void MvQFileWatcher::start(FILE* f,const string& path)
{
	if(file_ == 0 && f != 0)
	{
		file_ = f;
		
		//int n=fileno(f);
		
		if(!watcher_)
		{
		  	watcher_=new QFileSystemWatcher(this);
			watcher_->addPath(QString::fromStdString(path));
		
			connect(watcher_,SIGNAL(fileChanged(const QString&)),
				this,SLOT(slotInput(const QString&)));
		}		
	}
}


void MvQFileWatcher::slotInput(const QString&)
{
	char buf[1024];

	fflush(file_);
	
	if(fgets(buf,sizeof(buf),file_))
	{
		if(buf[0]) buf[strlen(buf)-1] = 0;
		emit ready(buf);
	}
	//else 
	//	emit done(file_);
}
