///
/// \file ReadFile.cc
/// \author kyle 
/// \created 2023-10-11
/// \brief ReadFile tests reading a file.
///
/// \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 <cstdint>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>


int
readFile(const std::string path)
{
	std::cout << "[+] opening " << path << "\n";
	std::ifstream input(path, std::ios::in);

	if (!input.good()) {
		std::cerr << "[!] failed to open " << path << "\n";
		input.close();
		return -1;
	}

	std::cout << "[+] reading from " << path << "\n";
	std::vector<std::vector<uint8_t>> doc;
	while (input.good()) {
		std::string temp;
		while (std::getline(input, temp)) {
			std::cout << "[+] line: " << temp << "\n";
			std::vector<uint8_t> row(temp.begin(), temp.end());
			doc.push_back(row);
		}
	}

	std::cout << "[+] finished reading document\n";
	std::cout << "\tgood: " << input.good() << "\n";
	std::cout << "\tfail: " << input.fail() << "\n";
	std::cout << "\t bad: " << input.bad() << "\n";
	std::cout << "\t eof: " << input.eof() << "\n";

	input.close();

	std::cout << "[+] dumping document of " << doc.size() << " lines.\n";
	for (size_t i = 0; i < doc.size(); i++) {
		std::cout << "line " << std::setw(3) << i << ": ";
		std::copy(doc[i].begin(), doc[i].end(),
			  std::ostream_iterator<uint8_t>(std::cout, ""));
		std::cout << "\n";
	}

	return 0;
}


int
main(int argc, char *argv[])
{
	for (int i = 1; i < argc; i++) {
		std::cout << "[+] input file: " << argv[i] << "\n";
		if (readFile(std::string(argv[i])) != 0) {
			std::cerr << "[!] failed\n";
		} else {
			std::cout << "[+] OK\n";
		}
	}
}