/**
  * pixwerx - a miniature 3D engine
  *
  * (c) Hartmut Seichter 2017-2018
  *
  */
#include <pw/core/core.hpp>
#include <pw/scripting/script.hpp>


#include <string>

#include <argagg/include/argagg/argagg.hpp>

#include <iostream>
#include <fstream>
#include <sstream>

int main(int argc,const char** argv) {

    argagg::parser argparser {{
            { "help", {"-h", "--help"}, "shows this help message", 0},
            { "file", {"-f", "--file"}, "load file to run", 1}
                              }};

    argagg::parser_results args;

    std::ostringstream usage;
    usage
            << "pixwerx rendering engine\n"
            << '\n'
            << "Usage: " << argv[0] << " [--help] [--file filename.lua]\n"
            << '\n';


    try {

        args = argparser.parse(argc,argv);

    } catch (std::exception &e) {



        argagg::fmt_ostream help(std::cerr);

        help << usage.str() << argparser << '\n'
             << "Encountered exception while parsing arguments: " << e.what()
             << '\n';

        return -1;
    }


    // run a file
    if (args["file"]) {

        std::ifstream input;

        input.open(args["file"].as<std::string>(),std::ifstream::in);

        if (!input.is_open()) {

            std::cerr << "cannot open '" << args["file"].as<std::string>() << "'" << std::endl;

            return -1;
        }

        // read as string
        std::ostringstream sout;
        std::copy(std::istreambuf_iterator<char>(input),
                  std::istreambuf_iterator<char>(),
                  std::ostreambuf_iterator<char>(sout));

        input.close();

        pw::script::initialize();

        pw::script s;

        return s.eval(sout.str().c_str());

    // show help
    } else if (args["help"]) {

        argagg::fmt_ostream help(std::cerr);
        help << usage.str() << argparser;

    }

    return 0;
}
