/*
	GameEngine and Editor
	by John Ryland
	Copyright (c) 2023
*/

////////////////////////////////////////////////////////////////////////////////////
//	MakeHeader

#include <iostream>
#include <iterator>
#include <fstream>
#include <iomanip>
#include "Utilities.h"

int main(int argc, char* argv[])
{
    // Check args
    if (argc != 4 || argv[2][0] != '-' || argv[2][1] != 'o' || argv[2][2] != '\0')
        Utilities::fail("Usage: %s input-file-name -o output-file-name\n", argv[0]);

    // Open input
    std::ifstream inputStream(argv[1], std::ios::binary);
    if (inputStream.fail())
        Utilities::fail("Couldn't open file for reading: %s\n", argv[1]);
    inputStream.unsetf(std::ios::skipws);

    // Read input
    std::istream_iterator<uint8_t> start(inputStream), end;
    std::vector<uint8_t> data(start, end);

    // Open output
    std::string outputFileName = argv[3];
    std::string outputVariable = Utilities::remove_extension(Utilities::base_name(outputFileName));
    std::replace(outputVariable.begin(), outputVariable.end(), ' ', '_');
    std::replace(outputVariable.begin(), outputVariable.end(), '-', '_');
    std::ofstream outputStream(outputFileName);
    if (outputStream.fail())
        Utilities::fail("Couldn't open file for writing: %s\n", argv[1]);

    // Write output
    outputStream << "#pragma once" << std::endl;
    outputStream << "// Generated with:" << std::endl;
    outputStream << "//   " << argv[0] << " " << argv[1] << " " << argv[2] << " " << argv[3] << std::endl;
    outputStream << "#include <cstdint>" << std::endl;
    outputStream << "static" << std::endl << "const uint8_t " << outputVariable;
    outputStream << "[] =" << std::endl << "{" << std::endl << "   ";
    int index = 0;
    for (uint8_t byte : data)
    {
        outputStream << " 0x" << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(byte) << ",";
        if ((++index % 16) == 0)
            outputStream << std::endl << "   ";
    }
    // Add a NUL terminator (should make this an option, default should be not to add it)
    // outputStream << " 0x00";
    outputStream << std::endl << "};" << std::endl;

    // Done
    std::cout << "Success!" << std::endl;
    return 0;
}
