#pragma once
#include "scene_parser.h"
#include "../output_helpers.h"
#include "token.h"

SceneParser::SceneParser(Scene* scene, const char* path) {
	Token::init();

	_scene = scene;

	_file = file_get_file(path);
	if (_file==NULL) throw glLibError("Could not open file!");
	_current_position = 0;
	_left = strlen(_file);

	_tokens = new vector<Token*>();
	current_token = NULL;

}
SceneParser::~SceneParser() {
	delete_token();

	delete _tokens;

	free((void*)(_file));

	Token::deinit();
}

int SceneParser::next_token(SCENE_TOKEN_TYPE acceptable_types, Token** result) {
	output_change_stack(1);
	delete_token();

	const char* loc_pointer = _file + _current_position;

	if (_left>0) {
		SCENE_TOKEN_TYPE t(0,0,0,0);
		while (t<STT_ALL) {
			t.increment();
			if (!(t&acceptable_types)) continue;
			//output_debug("Checking if it's "+t.get_as_string(),0);
			//printf("Checking token\n  ");t.print();printf("\n  Has pattern \"%s\".\n",(*Token::names)[t]->regex->c_str());

			int loc_end;
			bool success = (*Token::regexes)[t]->find_from_start(loc_pointer,_left,&loc_end);
			if (success) {
				//printf("Got token ");t.print();printf("!\n");
				//output_debug("Parser is making a new token.",0);
				current_token = new Token(string(loc_pointer,loc_end),t);
				advance(loc_end);
				break;
			}
		}

		*result = current_token;
		if (current_token==NULL) {
			output_change_stack(-1);
			return -1; //Couldn't find a token that matches!
		}
		output_change_stack(-1);
		return 1; //More tokens are available.
	}
	output_change_stack(-1);
	return 0; //No more tokens.
}
void SceneParser::kill_line(void) {
	const char* loc_pointer = _file + _current_position;

	int loc_start,loc_end;
	if ( (*Token::regexes)[STT_NEWLINE]->find_in(loc_pointer,_left,&loc_start,&loc_end) ) {
		advance(loc_end);
	}
	else if ( (*Token::regexes)[STT_EOF]->find_in(loc_pointer,_left,&loc_start,&loc_end) ) {
		advance(loc_end);
	}
	else {
		throw glLibError("Could not advance to the end of the line!");
	}
}

void SceneParser::print_remaining(int cutoff) {
	const char* pointer = _file + _current_position;
	if (cutoff==-1) {
		printf("%s",pointer);
	}
	else {
		char c; int i=0;
		while ((c=pointer[i])&&i<cutoff) {
			printf("%c",c);
			++i;
		}
	}
}