#include <stream_io.h>
#include <inttypes.h>
#include <boost/make_shared.hpp>
#include <stdio.h>
#include <iostream>

#define MAX_SIZE 200UL*1024ULL*1024ULL

using namespace std; 

CStreamIO::CStreamIO(const char* name, Path p):
	CRunnable( name ),
	path_( p->clone()->findByName( name ) ),
	stream_( IStream::create( p->findByName( name ) ) ),
	mutex_( CMtx::AttrRecursive(), "FILEMTX" )
{
}

StreamIO CStreamIO::create( const char* name, Path p)
{
	return boost::make_shared<CStreamIO>( name, p );
}

void* CStreamIO::threadBody()
{

	uint64_t got = 0;
	int nWords, nFrames, nBytes;
	std::vector<uint8_t> buf;
        buf.reserve(MAX_SIZE);  /* can cast location of first element to array pointer
                                   if we don't resize again */
	try {
		while(1)
		{
			got = stream_->read( (uint8_t *) ( &buf[0] ), MAX_SIZE, CTimeout(-1));
			if( !got )
			{
			}
			else
			{
				
		nWords = (got - 9) / 4; // header = 4 bytes, footer = 1 byte, data = 32bit words.
		nBytes = (got - 9); // header = 4 bytes, footer = 1 byte, data = 32bit words.
		nFrames = (buf[1]<<4) | (buf[0] >> 4);
		cout << "got = " << got << " bytes (" << nWords << " words) on " << path_->toString().c_str() << ". Frame # " << nFrames << endl;
				tryWriteFile( (char *) ( &buf[0] ), got );
			}
		}
	} catch( IntrError e )
	{

	}
	return NULL;
}


void CStreamIO::openFile( const char* file_name)
{
	CMtx::lg GUARD( &mutex_ );
	if( file_.is_open() )
		file_.close();

	file_.open( file_name );
}

void CStreamIO::closeFile()
{
	CMtx::lg GUARD( &mutex_ );
	if( file_.is_open() )
		file_.close();
}

bool CStreamIO::tryWriteFile(const char *data, uint64_t size)
{
	CMtx::lg GUARD( &mutex_ );
	if( !file_.is_open() )
		return false;

	file_.write( data, size );
	return true;
}

CStreamIO::~CStreamIO()
{
	closeFile();
	threadStop();
}
