#include "test.h"

#include <fstream>

#include "contrib/ozstream.hpp"
#include "file_line_provider.h"
#include "mock_log_lines.h"

TEST_CASE("readfile") {
	list<string> data = {
		"hello", "there", "good", "people", "and",
		"welcome", "to", "the", "test"};

	filesystem::path filename = filesystem::weakly_canonical("/tmp/.logserver_filelinetest.dat");
	ofstream fout(filename);
	CHECK(fout.good());
	for (const auto &x : data) fout << x << endl;
	fout.flush();
	MockLogLines ll;
	ll.expect(data);
	FileLineProvider flp(&ll, filename);
	flp.start();
	while (!ll.eof()) {
		usleep(1000);
	}
	CHECK(ll.no_expectations());
	ll.expect("more data");
	ll.expect("and yet more");

	fout << "more data" << endl;
	fout.flush();
	usleep(10000);
	fout << "and yet more" << endl;
	fout.flush();
	fout.close();
	ifstream fin(filename);
	assert(fin.good());
	fin.close();
	while (!ll.no_expectations()) {
		usleep(1000);
	}
	// live updated file should no longer signal eof
	CHECK(ll.eof() == false);
}

TEST_CASE("read zip file") {
	list<string> data = {
		"hello", "there", "good", "people", "and",
		"welcome", "to", "the", "test"};

	filesystem::path filename = filesystem::weakly_canonical("/tmp/.logserver_filelinetest.dat");
	ofstream fout(filename);
	zstream::ogzstream zout(fout);

	for (const auto &x : data) zout << x << endl;
	zout.close();

	MockLogLines ll;
	ll.expect(data);
	FileLineProvider flp(&ll, filename);
	flp.start();
	while (!ll.eof()) {
		usleep(1000);
	}
	CHECK(ll.no_expectations());
}
