/***************************** 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 "Input.h"

#include <QSocketNotifier>


Input::Input():
	file_(0),
	notifier_(0)
{
}

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

void Input::stop()
{
	if(file_)
	{
		if(notifier_)
		{
		  	delete notifier_;
			notifier_=0;
		}	
		file_ = 0;
	}
}

void Input::start(FILE* f)
{
	if(file_ == 0 && f != 0)
	{
		file_ = f;
		
		int n=fileno(f);
		
		if(!notifier_)
		{
		  	//WARNING!!!!
			//It works only on UNIX!!!
		  	notifier_=new QSocketNotifier(n,QSocketNotifier::Read);
		
			connect(notifier_,SIGNAL(activated(int)),
				this,SLOT(slotInput(int)));
		}		
	}
}


void Input::slotInput(int)
{
	char buf[1024];

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