#include "Lexesis/backendmanager.h"
#include "Lexesis/backends/cpp.h"
#include "Lexesis/driver.h"
#include "Lexesis/inputparser.h"
#include "optparse.h"

#include <fstream>
#include <iostream>

int main(int argc, char** argv) {
    optparse::OptionParser parser = optparse::OptionParser().description("Lexesis, the lexical analyser generator.").usage("Lexesis [-d <outputdir>] [-l <language>] [-n <lexername>] <inputfile.lxs>");
    parser.add_help_option(true);
    parser.version("%prog 1.0");
    parser.add_option("-d", "--outputdir").dest("outputdir").help("Output the generated files to this directory\n[default: .]").metavar("<directory>").set_default(".");
    parser.add_option("-l", "--lang", "--language").dest("language").help("The programming language to generate source files for\n[default: c++]").metavar("<language>").set_default("c++");
    parser.add_option("-n", "--name").dest("lexername").help("Use this name for the generated lexer, the default is based on the input file name").metavar("<lexername>");

    optparse::Values options = parser.parse_args(argc, argv);
    std::vector<std::string> args = parser.args();

    if (args.size() != 1) {
        parser.print_usage(std::cerr);
        return 1;
    }

    std::ifstream infile(args[0]);
    if (!infile.good()) {
        std::cerr << "Could not open file '" << args[0] << "' for reading" << std::endl;
        return 1;
    }

#ifdef _WIN32
    const char PATHSEP = '\\';
#else
    const char PATHSEP = '/';
#endif

    std::string lexername = options["lexername"];

    if (!lexername.length()) { //The option is empty
        if (args[0].length() >= 4 && args[0].substr(args[0].length() - 4, 4) == ".lxs") {
            lexername = args[0].substr(0, args[0].length() - 4); //Drop the .lxs

        } else {
            lexername = args[0];
        }

        std::size_t pos;
        // '/' can be used on most platforms (even windows)
        pos = lexername.find_last_of('/');
        if (pos != lexername.npos) {
            lexername = lexername.substr(pos + 1);
        }

        // strip platform specific as well
        pos = lexername.find_last_of(PATHSEP);
        if (pos != lexername.npos) {
            lexername = lexername.substr(pos + 1);
        }

    }

    std::unique_ptr<lxs::BackendManager> backends(new lxs::BackendManager());
    backends->registerBackend(std::unique_ptr<lxs::Backend>(new lxs::backends::CppBackend()));
    try {
        lxs::Driver driver(std::move(backends), infile, options["outputdir"], options["language"], lexername);
        return driver.run();
    } catch (std::exception &err) {
        std::cout << err.what() << std::endl;
        return 1;
    }
}
