// -*- c++ -*-
// Distributed under the BSD 2-Clause License.
// See accompanying file LICENSE for details.
#include "task_fn.h"

#include <iostream>
#include <fstream>
#include <cassert>

#include "ctor.h"
#include "execute.h"
#include "util.h"

TaskFn::TaskFn(const ctor::build_configuration& config_, const ctor::settings& settings_,
               const std::string& sourceDir_, const ctor::source& source)
	: Task(config_, settings_, sourceDir_)
	, sourceFile(sourceDir_)
	, config(config_)
	, settings(settings_)
{
	sourceFile /= source.file;

	std::filesystem::create_directories(std::filesystem::path(settings.builddir) / sourceFile.parent_path());

	target_type = config.type;
	source_language = source.language;

	if(source.output.empty())
	{
		std::cerr << "Missing output file for functional target\n";
		exit(1);
	}

	_targetFile = source.output;
}

bool TaskFn::dirtyInner()
{
	if(!std::filesystem::exists(sourceFile))
	{
		//std::cout << "Missing source file: " << std::string(sourceFile) << "\n";
		return true;
	}

	if(!std::filesystem::exists(targetFile()))
	{
		//std::cout << "Missing targetFile\n";
		return true;
	}

	if(std::filesystem::last_write_time(sourceFile) >
	   std::filesystem::last_write_time(targetFile()))
	{
		//std::cout << "The targetFile older than sourceFile\n";
		return true;
	}

	return false;
}

int TaskFn::runInner()
{
	if(!std::filesystem::exists(sourceFile))
	{
		std::cout << "Missing source file: " << sourceFile.string() << "\n";
		return 1;
	}

	if(settings.verbose >= 0)
	{
		std::string output = "Fn " +
			sourceFile.lexically_normal().string() + " => " +
			targetFile().lexically_normal().string() + '\n';
		std::cout << output << std::flush;
	}

	return config.function(sourceFile.string(),
	                       targetFile().string(),
	                       config,
	                       settings);
}

int TaskFn::clean()
{
	if(std::filesystem::exists(targetFile()))
	{
		std::cout << "Removing " << targetFile().string() << "\n";
		std::filesystem::remove(targetFile());
	}

	return 0;
}

std::vector<std::string> TaskFn::depends() const
{
	return {};
}

std::string TaskFn::target() const
{
	return _targetFile.string();
}

std::filesystem::path TaskFn::targetFile() const
{
	return std::filesystem::path(settings.builddir) / sourceDir / _targetFile;
}

bool TaskFn::derived() const
{
	return false;
}

std::string TaskFn::toJSON() const
{
	return {}; // TODO: Not sure how to express this...
}

std::string TaskFn::source() const
{
	return sourceFile.string();
}