///
/// \file File.cc
/// \author kyle 
/// \created 10/11/23
/// \brief
///
/// \section COPYRIGHT
/// Copyright 2023 K. Isom <kyle@imap.cc>
///
/// Permission to use, copy, modify, and/or distribute this software for
/// any purpose with or without fee is hereby granted, provided that the
/// above copyright notice and this permission notice appear in all copies.
///
/// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
/// WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
/// WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
/// BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
/// OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
/// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
/// ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
/// SOFTWARE.
///

#include <filesystem>
#include <utility>
#include "File.h"


File::File(std::string fPath)
    : path(fPath), readOnly(false)
{

}


File::File(std::filesystem::path fPath)
    : path(std::move(fPath)), readOnly(false)
{

}


const std::string File::Path()
{
	return this->path.string();
}


void File::SetPath(const std::string &fPath)
{
	File::path = fPath;
}


OptOutFileStream File::Flush()
{
	// Exit early if we shouldn't be writing to the file.
	if (this->IsReadOnly()) {
		return std::nullopt;
	}

	if (!this->Exists()) {
		if (!this->IsWriteable()) {
			return std::nullopt;
		}

		return {new std::ofstream(this->path, std::ios::out|std::ios::trunc)};
	}

	return {new std::ofstream(this->path, std::ios::out)};
}


OptInFileStream
File::Refresh()
{
	if (!this->Exists()) {
		return std::nullopt;
	}

	return {new std::ifstream(this->path, std::ios::in)};
}


size_t
File::Size()
{
	return std::filesystem::file_size(this->path);
}


bool
File::Exists()
{
	return std::filesystem::exists(this->path);
}


static bool
checkAccess(std::filesystem::path path, std::filesystem::perms mode, bool checkParent)
{
	if (!std::filesystem::exists(path) && checkParent) {
		auto fullPath = std::filesystem::absolute(path);
		auto parent = fullPath.parent_path();
		auto dirEnt = std::filesystem::directory_entry(parent);
		auto perms = dirEnt.status().permissions();
		return (perms & mode) != std::filesystem::perms::none;
	}

	return (status(path).permissions() & mode) != std::filesystem::perms::none;
}


bool
File::IsWriteable()
{
	return checkAccess(this->path, std::filesystem::perms::owner_write, true);
}


bool
File::IsReadable()
{
	return checkAccess(this->path, std::filesystem::perms::owner_read, false);
}


bool
File::IsReadWriteable()
{
	auto checkMode = std::filesystem::perms::owner_read | std::filesystem::perms::owner_write;
	return checkAccess(this->path, checkMode, true);
}
