#include "parse_driver.hpp"
#include "scanner.hpp"
#include <sstream>

file_mgr::file_mgr() : file_offset(0) {
    line_offsets.push_back(0);
}

void file_mgr::write(const char* buf, size_t len) {
    string_stream.write(buf, len);
    file_offset += len;
}

void file_mgr::mark_line() {
    line_offsets.push_back(file_offset);
}

void file_mgr::finalize() {
    file_contents = string_stream.str();
}

size_t file_mgr::get_index(int line, int column) const {
    assert(line > 0 && line <= line_offsets.size());
    return line_offsets.at(line-1) + column - 1;
}

size_t file_mgr::get_line_end(int line) const {
    if(line == line_offsets.size()) return file_contents.size();
    return get_index(line+1, 1);
}

void file_mgr::print_location(
        std::ostream& stream,
        const yy::location& loc,
        bool highlight) const {
    size_t print_start = get_index(loc.begin.line, 1);
    size_t highlight_start = get_index(loc.begin.line, loc.begin.column);
    size_t highlight_end = get_index(loc.end.line, loc.end.column);
    size_t print_end = get_line_end(loc.end.line);
    const char* content = file_contents.c_str();
    stream.write(content + print_start, highlight_start - print_start);
    if(highlight) stream << "\033[4;31m";
    stream.write(content + highlight_start, highlight_end - highlight_start);
    if(highlight) stream << "\033[0m";
    stream.write(content + highlight_end, print_end - highlight_end);
}

bool parse_driver::operator()() {
    FILE* stream = fopen(file_name.c_str(), "r");
    if(!stream) return false;
    yyscan_t scanner;
    yylex_init(&scanner);
    yyset_in(stream, scanner);
    yy::parser parser(scanner, *this);
    parser();
    yylex_destroy(scanner);
    fclose(stream);
    file_m->finalize();
    return true;
}

yy::location& parse_driver::get_current_location() {
    return location;
}

file_mgr& parse_driver::get_file_manager() const {
    return *file_m;
}

definition_group& parse_driver::get_global_defs() const {
    return *global_defs;
}
