//
// Copyright (c) 2010 Ronald Kluth
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

/**
 * @file TestOutputXmlFileWriter.cpp
 * @author Ronald Kluth
 * @date created at 2010/04/28
 * @brief Unit tests for class template XmlFileWriter
 * @since 0.1
 */

#include "global.h"
#include <Poco/File.h>

SUITE( CppLogUnitTest )
{
	struct TestXmlFileWriterFixture
	{
		typedef Log::XmlFileWriter< Infos > XmlFileWriterType;
		typedef std::tr1::shared_ptr< XmlFileWriterType > XmlFileWriterPtr;
		std::string fileNameBase;
		XmlFileWriterPtr xmlWriter;
		TestXmlFileWriterFixture()
		:	fileNameBase( "TestXmlFileWriter" )
		,	xmlWriter()
		{}
	};

	TEST_FIXTURE( TestXmlFileWriterFixture, NewFileAfterConstruction )
	{
		// a new file should have been opened during construction
		xmlWriter = XmlFileWriterType::create( fileNameBase, 3 );
		Poco::File file( fileNameBase + "_0.xml" );
		CHECK( file.exists() );
	}

	TEST_FIXTURE( TestXmlFileWriterFixture, Consume )
	{
		xmlWriter = XmlFileWriterType::create(
				fileNameBase, 3, "test_xml_file_writer", 4 );

		Point3d p3d = { 1, 2, 3 };
		xmlWriter->consume( 0,
				Log::Record( "test_xml_file_writer_consume" )
				+ StringInfo( "test_string_info" ) + PointInfo( p3d ) );
		xmlWriter.reset(); // should destroy the writer and close the file

		Poco::File file( fileNameBase + "_0.xml" );
		CHECK( file.exists() );

		std::ifstream is( (fileNameBase + "_0.xml").c_str(), std::ifstream::in );
		std::string line;
		std::getline( is, line );
		CHECK( find( line, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ) );

		std::getline( is, line );
		CHECK( find( line, "<test_xml_file_writer>" ) );

		std::getline( is, line );
		CHECK( find( line, "    <record>" ) );

		std::getline( is, line );
		CHECK( find( line, "        <text>test_xml_file_writer_consume</text>" ) );

		std::getline( is, line );
		CHECK( find( line, "        <test_string_info>test_string_info</test_string_info>" ) );

		std::getline( is, line );
		CHECK( find( line, "        <test_point_info>(1 2 3)</test_point_info>" ) );

		std::getline( is, line );
		CHECK( find( line, "    </record>" ) );

		std::getline( is, line );
		CHECK( find( line, "</test_xml_file_writer>" ) );
	}

	TEST_FIXTURE( TestXmlFileWriterFixture, LimitReachedStartNewFile )
	{
		xmlWriter = XmlFileWriterType::create(
				fileNameBase, 3, "test_xml_file_writer", 4 );

		int i = 4;
		while( i-- )
		{
			Point3d p3d = { 1, 2, 3 };
			xmlWriter->consume( 0,
					Log::Record( "test_xml_file_writer_consume" )
					+ StringInfo( "test_string_info" ) + PointInfo( p3d ) );
		}
		xmlWriter.reset(); // should destroy the writer and close the file

		Poco::File file( fileNameBase + "_1.xml" );
		CHECK( file.exists() );
	}
}
