#include <iostream>
#include "common.h"
#include "date.h"

namespace fs = std::filesystem;

const std::string LogFile::date()
{
	namespace C = std::chrono;
	namespace D = date;

	std::ostringstream str;
	auto tp = C::system_clock::now();
	auto dp = D::floor<D::days>(tp);
	auto yd = D::year_month_day {dp};
	auto tm = D::make_time(
	              C::duration_cast<C::milliseconds>(tp - dp));

	str << yd.year() << "-"
	    << static_cast<unsigned>(yd.month()) << "-"
	    << yd.day() << "_"
	    << tm.hours().count();
	return str.str();
}

void demo_perms(std::filesystem::perms p)
{
    using std::filesystem::perms;
    auto show = [=](char op, perms perm)
    {
        std::cerr << (perms::none == (perm & p) ? '-' : op);
    };
    show('r', perms::owner_read);
    show('w', perms::owner_write);
    show('x', perms::owner_exec);
    show('r', perms::group_read);
    show('w', perms::group_write);
    show('x', perms::group_exec);
    show('r', perms::others_read);
    show('w', perms::others_write);
    show('x', perms::others_exec);
    std::cerr << '\n';
}

LogFile::LogFile()
{
	base = fs::path("/var/log/" APP_NAME);
	try {
		if(fs::exists(base))
			if(not fs::is_directory(base))
				fs::remove(base);

		if(not fs::exists(base))
			fs::create_directories(base);

		if(fs::create_directory(base / ".test"))
			fs::remove(base / ".test");
	} catch (const std::exception& e) {
		std::cerr << e.what() << std::endl;
		stdout = true;
	}
}

void LogFile::change(refstream& fstr)
{
	if(stdout)
		return;

	if(not (std::addressof(fstr.get()) == std::addressof(stream)))
		fstr = std::ref(stream);

	std::string now = date();

	if(not (date_ == now)) {
		if(stream.is_open())
			stream.close();
		date_ = now;
	}

	if(not stream.is_open())
		stream.open(base / (date_ + ".log"));
}
