// Fill out your copyright notice in the Description page of Project Settings.

#include "PDB_viewer.h"
#include <chrono>
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <Misc/AssertionMacros.h>

IMPLEMENT_PRIMARY_GAME_MODULE(PDB_viewer, PDB_viewer, "PDB_viewer");

const char* PDB_viewer::LOG_FILE_NAME = "boost_log.txt";

void PDB_viewer::StartupModule()
{
	FString finalLogFilePath = FPaths::Combine(*FPaths::GameLogDir(), ANSI_TO_TCHAR(LOG_FILE_NAME));
	const char* finalLogFilePath_raw = TCHAR_TO_ANSI(*finalLogFilePath);
	fileLogSink = boost::make_shared<text_sink>();
	//check if existing log file is old, if it is - clear it
	std::chrono::seconds long_time_ago = std::chrono::duration_cast<std::chrono::seconds>((std::chrono::system_clock::now() - std::chrono::hours(12)).time_since_epoch());
	if (boost::filesystem::exists(finalLogFilePath_raw) && boost::filesystem::last_write_time(finalLogFilePath_raw) < long_time_ago.count())
	{
		UE_LOG(LogInit, Log, TEXT("Removing old boost sink at \"%s\""), finalLogFilePath_raw);
		boost::filesystem::remove(finalLogFilePath_raw);
	}
	UE_LOG(LogInit, Log, TEXT("Appending a boost sink to \"%s\""), *finalLogFilePath);
	//otherwise new logs will be appended
	fileLogSink->locked_backend()->add_stream(boost::make_shared<std::ofstream>(finalLogFilePath_raw, std::ios_base::out | std::ios_base::app));
	fileLogSink->locked_backend()->auto_flush(true);
	boost::log::core::get()->add_sink(fileLogSink);
}

void PDB_viewer::ShutdownModule()
{
	boost::log::core::get()->remove_sink(fileLogSink);
	fileLogSink->flush();
	fileLogSink.reset();
}

bool PDB_viewer::IsGameModule() const
{
	return true;
}
