#include "bod_cut_parser.h"
#include "../common/strutils.h"
//---------------------------------------------------------------------------------
bool bod_cut_parser::compile(token_stream& is, bob_dom_obinaryfilestream& os)
{
	os << bob_dom_cut::hdr_begin;
	
	bob_dom_cut *cut=loadCUT(is, &os, true);
	
	//if(cut)
		//cut->toFile(os);
	
	delete cut;
	
	os << bob_dom_cut::hdr_end;
	
	return cut!=NULL;
}
//---------------------------------------------------------------------------------
bob_dom_cut * bod_cut_parser::loadCUT(token_stream& is)
{
	bob_dom_obinaryfilestream *dummy=0;
	
	return loadCUT(is, dummy, false);
}
//---------------------------------------------------------------------------------
// this is bit weird function as it serves for 2 purposes: it can return loaded cut object
// or it can directly output parts of cut as it's being loaded
bob_dom_cut * bod_cut_parser::loadCUT(token_stream& is, bob_dom_obinaryfilestream *os, bool bDirectOutput)
{
	bod_text_parser::token *t;
	bob_dom_path *actPath=0;
	bob_dom_stat *actStat=0;
	bob_dom_cut *cut=new bob_dom_cut(m_settings);
	
	// used for direct output
	int pathCountOffset;
	int pathCount=0;
	
	bool bErrors=false;
	bool bRes=false;
	
	while(is.good() && is.tok()->type==token::t_hdrinfo){
		if(cut->info.text()!=0)
			error(is.tok(), S_Warning, "Header info already defined, last value will be used");
		cut->info.text(is.tok()->text);
		++is;
	}

	do{
		// VERSION
		t=is.tok();
		if(t==NULL || t->type!=token::t_text || strcmp(t->text, "VER")!=0)
			{ error(t ? t : is.previous(), S_Error, "Expected version specification"); break; }
		
		t=(++is).tok();
		if(t==NULL || t->type!=token::t_colon)
			{ error(t ? t : is.previous(), S_Error, "Expected ':' after '%s'", is.previous()->text); break; }
		
		if(!checkImmediatePlacement(is.previous(), is.tok())) 
			break;
		
		if((t=loadValue(++is))==NULL)
			break;
		if(!isinteger(t->text))
			{ error(t ? t : is.previous(), S_Error, "Expected version number after ':'"); break; }
			
		cut->version=atoi(t->text);
		
		if(cut->version > bob_dom_cut::supported_version)
			error(is.tok(), S_Warning, "File version is %d, supported version is %d", cut->version, bob_dom_cut::supported_version);
		
		if(bDirectOutput){
			cut->info.toFile(*os);
			*os << cut->version; 
			/*	
				we must output the path count right now, 
				but we will rewrite it once we finish
			*/
			pathCountOffset=(int)os->tell();
			*os << pathCount; 
		}
		
		while(is.good()){
			t=is.tok();
			
			if(t->type==token::t_openBracket){
				if(actPath==NULL){
					error(t, S_Error, "Block unexpected here.");
					break;
				}
				else{
					bErrors|=!loadFrame(actPath, ++is); 
				}
			}
			
			else{
				if(actPath && bDirectOutput){
					pathCount++;
					actPath->toFile(*os, cut->version);
					cut->removeChild(--cut->end());
				}
				if((actPath=loadPath(cut, is))==NULL)
					break;
				
				if(!is.good()){
					error(is.previous(), S_Error, "Missing Frame declaration after Body declaration");
					break;
				}
			}
			bRes=!bErrors;
		}
	}
	while(false);
	
	if(actPath && bDirectOutput){
		pathCount++;
		actPath->toFile(*os, cut->version);
		cut->removeChild(--cut->end());
	}
	
	if(bRes==false){
		delete cut;
		return NULL;
	}
	else{
		if(bDirectOutput){	
			size_t endPos=os->tell();
			os->seek(pathCountOffset, bob_filestream::seek_begin);
			*os << pathCount;
			os->seek((int)endPos, bob_filestream::seek_begin);
		}
		return cut;
	}
}
//---------------------------------------------------------------------------------
bob_dom_path * bod_cut_parser::loadPath(bob_dom_cut *cut, token_stream& is)
{
	bob_dom_path *path=cut->createChild();

	bool bRes=false;
	
	bod_text_parser::token *t;
	
	do{
		t=is.tok();
		
		// index
		if(t==NULL || t->type!=token::t_text || strcmp(t->text, "P")!=0)
			{ error(t ? t : is.previous(), S_Error, "Expected body declaration starting with Path ID (P)."); break; }
		if((t=loadValue(++is))==NULL)
			break;
		if(!isinteger(t->text))
			{ error(t, S_Error, "Body declaration: Expected number after '%s'", is.previous()->text); break; }
		else
			path->partIdx=atoi(t->text);
		
		// body id
		t=is.tok();
		if(t==NULL || t->type!=token::t_text || strcmp(t->text, "B")!=0)
			{ error(t ? t : is.previous(), S_Error, "Body declaration: Expected Body ID (B)."); break; }
		if((t=loadValue(++is))==NULL)
			break;
		if(cut->version < 6 && !isinteger(t->text)) {
			error(t, S_Error, "Body declaration: body ID is string but cut version is %d. Change version to 6.", cut->version);
			break;
		}
		path->bodyId(t->text);
		
		bRes=true;
		
		bool bCockpit=false, bParentIdx=false, bName=false, bNotes=false;
		
		// cockpit, name, flag, body flag, inner bob, notes
		while(is.good()){
			t=is.tok();
			if(t->type==token::t_openBracket)
				break;
				
			if(t->type!=token::t_text || strlen(t->text) > 1){
				error(t, S_Error, "Unexpected here: '%s'", t->getText());
				bRes=false;
				break;
			}
			
			char ch=t->text[0];
			
			// cockpit index
			if(ch=='C'){
				if((t=loadValue(++is))==NULL)
					{ bRes=false; break; }
				if(!isinteger(t->text))
					{ error(t, S_Error, "Body declaration: Expected number after '%s'", is.previous()->text); bRes=false; break; }
				
				if(bCockpit)
					error(t, S_Warning, "Cockpit index already defined, last value will be used");
				
				bCockpit=true;
				path->cockpitIdx=atoi(t->text);
			}
			// parent index
			else if(ch=='F'){
				if((t=loadValue(++is))==NULL)
					{ bRes=false; break; }
				if(!isinteger(t->text))
					{ error(t, S_Error, "Body declaration: Expected number after '%s'", is.previous()->text); bRes=false; break; }
				
				if(bParentIdx)
					error(t, S_Warning, "Parent index already defined, last value will be used");
					
				bParentIdx=true;
				path->parentIdx=atoi(t->text);
			}
			// name
			else if(ch=='N'){
				const char *name=loadString(++is);
				if(name==0) break;
				
				if(bName)
					error(t, S_Warning, "Name already defined, last value will be used");
				
				bName=true;
				path->name.m_text=(char*)name;
			}
			// embedded bob
			else if(ch=='L'){
				t=(++is).tok();
				if(t==NULL || t->type!=token::t_openBracket)
					{ error(t ? t : is.previous(), S_Error, "Expected beginning of block after '%s'", is.previous()->getText()); bRes=false; break; }
				else{
					++is;
					path->bob=loadBOB(is, true);
					if(path->bob==NULL) {
						bRes=false; break;
					}
				}
			}
			// notes
			else if(ch=='T'){
				if(loadNote(path, is)==false) 
					{ bRes=false; break; }
				
				if(bNotes)
					error(t, S_Warning, "Notes already defined, last definition will be used");
				
				bNotes=true;
			}
			// constants
			else if(ch=='K'){
				int count;
				bob_dom_constants::constant c;
				
				if(!loadIntValue(++is, &count)){
					bRes=false; break;
				}
				for(int i=0; i < count; i++){
					loadIntValue(is, &(c.a));
					if(!loadDoubleValue(is, &(c.b))){
						bRes=false; break;
					}
					path->constants.values.push_back(c);
				}
				if(bRes==false) break;	
			}
			// last try if it's a body flag (Camera, Light, Direct, v). It must not be followed by semicolon
			else{
				t=(++is).tok();
				if(t){
					if(t->type==token::t_semicolon)
						{ error(t, S_Error, "Invalid Body flag specification '%s': flag must NOT be followed by ';'", is.previous()->text); bRes=false; break; }
					if(t->type==token::t_colon)
						{ error(t, S_Error, "Unexpected here: ':'"); bRes=false; break; }
				}
				if(!(ch >='a' && ch<='z' || ch>='A' && ch<='Z'))
					{ error(is.previous(), S_Error, "Invalid Body flag specification '%c': flag must be alphabetic character", ch); bRes=false; break; }
				if(ch!='c' && ch!='l' && ch!='d' && ch!='v' && ch!='b' && ch!='j' && ch!='u')
					{ error(is.previous(), S_Warning, "Body flag '%c' out of safe limits, known values are 'c', 'l', 's', 'v', 'p', 'j', 'u'", ch); }
				
				//path->bodyFlag=ch - 'b';
				/*
					TODO: translate the char into body flag and
					OR the flags together
				
				*/
				/*
					if(bodyFlags & BodyFlags::fBody)
					os << "b ";
					if(bodyFlags & BodyFlags::fScene)
						os << "j ";
					int i=bodyFlags & 0x3F;
					if(i) 
						os << (char) ('b' + i) << ' ';
				*/
				switch(ch){
					// both probably mean 'scene'
					case 'j': // no break
					case 'u':
						path->bodyFlags|=bob_dom_path::fScene;
						break;
					case 'b':
						path->bodyFlags|=bob_dom_path::fBody;
						break;
					default:
						path->bodyFlags|=ch - 'b';
				}
			}
		}
	}
	while(false);
	
	if(bRes && t && t->type!=token::t_openBracket)
		{ error(is.previous(), S_Error, "Unexpected end of document found when looking for beginning of Frame block"); bRes=false; }
	
	if(bRes==false){
		cut->removeChild(cut->end() - 1);
		path=NULL;
	}
	
	return path;
}
//---------------------------------------------------------------------------------
bool bod_cut_parser::loadNote(bob_dom_path *path, token_stream& is)
{
	bob_note *n;
	bod_text_parser::token *t;
	bool bEnd=false;
	
	path->notes().removeChildren();
	
	++is;
	do{
		n=path->notes().createChild();
		// left
		if((t=loadValue(is))==NULL)
			break;
		if(!isinteger(t->text))
			{ error(t, S_Error, "Expected number"); break; }
		n->value=atoi(t->text);
		
		if(n->value==-1) {	
			path->notes().removeChild(path->notes().end() - 1);
			bEnd=true;
			break; // end of notes
		}
		
		// right 
		n->text=loadString(is);
		if(n->text==NULL){
			path->notes().removeChild(path->notes().end() - 1);
			break;
		}
	}
	while(is.good());
	
	if(bEnd==false && is.eof())
		error(is.previous(), S_Error, "Unexpected end of document found while looking for end of Notes (-1)");
	
	return t!=NULL;
}
//---------------------------------------------------------------------------------
#ifdef X2BC_USE_INI_FORMATS
bool bod_cut_parser::loadFrame(bob_dom_path *path, token_stream& is)
{
	token *t;
	bool bRes=false;
	
	bob_dom_stat *stat=path->createChild();
	const Settings::StatFormat *f;
	
	// frame id
	t=is.tok();
	if(t==NULL)
		error(is.previous(), S_Error, "Expected frame ID"); 
	else if(loadValue(is)){
		if(!(isinteger(t->text) || ishexa(t->text)))
			error(t, S_Error, "Expected frame ID in decadic or hexadecimal format");
		else{
			if(t->text[0]=='0' && ((t->text[1] | 0x20) == 'x'))
				stat->frameId=hextoi(t->text);
			else
				stat->frameId=atoi(t->text);
				
			f=m_settings->findStatFormat(stat->frameId);
			if(f==NULL)
				error(is.previous(), S_Error, "Cannot find frame format 0x%X - cannot continue", stat->frameId);
			else
				bRes=true;
		}
	}
	
	if(bRes){
		for(Settings::StatFormat::const_iterator &it=f->tokens.begin(); it!=f->tokens.end(); ++it){
			for(int i=0; i < it->count; i++){
				if((t=loadValue(is))==NULL){
					error(is.previous(), S_Error, "Frame format 0x%X requires %d numbers", stat->frameId, f->cumulativeTokenCount);
					bRes=false;
					goto the_end; // yes it's a GOTO so kill me
				}
				if(!isfloat(t->text)){
					error(t, S_Error, "Expected number (integer or float)"); 
					bRes=false;
					goto the_end;
				}
				
				if(it->numFormat->outformat==Settings::NumberFormat::Integer && !isinteger(t->text))
					error(t, S_Warning, "Expected integer not float");
				
				unsigned int v;
				double d=(atof(t->text) / it->numFormat->multiplier);
				
				// this is same as v=(unsigned int) d;
				// but is uses normal rounding - not round toward zero, this is important 'cos otherwise there will 
				// be error + 1 in the resulting int (only if the resulting double has fraction part)
				__asm{
					fld qword ptr d
					fistp dword ptr v
				}
				
				stat->push_back(v);
			}
		}
		size_t pos=is.tell();
		while((t=is.tok()) && t->type!=token::t_closeBracket){
			++is;
		}
		if(t==NULL){
			error(is.previous(), S_Error, "Unexpected end of document found while looking for end of frame block '}'");
			bRes=false;
		}
		else if(is.tell()!=pos){
			error(is.previous(), S_Error, "Too many parameters in frame declaration, expected %d numbers", f->cumulativeTokenCount);
			bRes=false;
		}
		++is; // advance past the end bracket
	}
	
the_end:
	if(bRes==false)
		path->removeChild(path->end() - 1);
	return bRes;
}
//---------------------------------------------------------------------------------
#else // !defined(X2BC_USE_INI_FORMATS)
bool bod_cut_parser::loadFrame(bob_dom_path *path, token_stream& is)
{
	token *t;
	bool bRes=false;
	
	bob_dom_frame *frame=path->createChild();
	int flags;
	
	// frame flags
	t=is.tok();
	if(t==NULL)
		error(is.previous(), S_Error, "Expected frame ID"); 
	else if(loadValue(is)){
		if(!(isinteger(t->text) || ishexa(t->text)))
			error(t, S_Error, "Expected frame ID in decadic or hexadecimal format");
		else{
			if(t->text[0]=='0' && ((t->text[1] | 0x20) == 'x'))
				flags=hextoi(t->text);
			else
				flags=atoi(t->text);
			
			if(flags & CUT_F_POSBEZINFO)
				error(NULL, S_Warning, "CUT_F_POSBEZINFO encoutered - don't know how to compile");
			if(flags & CUT_F_SAMESCALE)
				error(NULL, S_Warning, "CUT_F_SAMESCALE encoutered");
			
			if(flags & ~bob_dom_frame::flagMask)
				error(is.tok(), S_Warning, "Unsupported bits set in frame flags - normalizing flags, unsupported values will not be compiled");
			
			flags&=bob_dom_frame::flagMask;
			frame->flags=flags;
			
			bRes=true;
		}
	}
	
	while(bRes){
		static const char *pos_context = "frame: position: ";
		static const char *rot_context ="frame: rotation: ";
		static const char *tpos_context ="frame: target position: ";
		static const char *troll_context ="frame: roll angle: ";
		static const char *fov_context ="frame: FOV: ";
		static const char *color_context ="frame: RGB: ";
		static const char *len_context ="frame: length: ";
		static const char *idx_context ="frame: index: ";
		
		if((flags & CUT_F_SAMEPOS)==0){
			loadIntValue(is, &(frame->position.x), pos_context);
			loadIntValue(is, &(frame->position.y), pos_context);
			if((bRes=loadIntValue(is, &(frame->position.z), pos_context))==false) break;
			
			if(flags & CUT_F_POSTCBINFO) {
				frame->pos_tcb_info=new bob_dom_frame::tcb_info();
				if((bRes=loadTCBInfo(is, frame->pos_tcb_info))==false) break;
			}
		}
		if((flags & CUT_F_SAMEROT)==0 && (flags & CUT_F_ROT)){
			frame->rotation=new bob_dom_frame::angle_axis();
			loadDoubleValue(is, &(frame->rotation->angle), rot_context);
			loadDoubleValue(is, &(frame->rotation->x), rot_context);
			loadDoubleValue(is, &(frame->rotation->y), rot_context);
			if((bRes=loadDoubleValue(is, &(frame->rotation->z), rot_context))==false) break;
			
			if(flags & CUT_F_ROTTCBINFO){
				frame->rot_tcb_info=new bob_dom_frame::tcb_info();
				if((bRes=loadTCBInfo(is, frame->rot_tcb_info))==false) break;
			}
		}
		if(flags & CUT_F_TARGETPOS){
			if((flags & CUT_F_SAMETARGET)==0){
				frame->targetPos=new bob_dom_frame::point3d();
				loadIntValue(is, &(frame->targetPos->x), tpos_context);
				loadIntValue(is, &(frame->targetPos->y), tpos_context);
				if((bRes=loadIntValue(is, &(frame->targetPos->z), tpos_context))==false) break;
			}
			if((flags & CUT_F_SAMEROT)==0){
				if((bRes=loadDoubleValue(is, &(frame->rollAngle), troll_context))==false) break;
			}
			if(flags & CUT_F_TPOSTCBINFO){
				frame->tpos_tcb_info=new bob_dom_frame::tcb_info();
				if((bRes=loadTCBInfo(is, frame->tpos_tcb_info))==false) break;
			}
		}
		if((flags & CUT_F_SAMEFOV)==0 && flags & CUT_F_FOV){
			if((bRes=loadDoubleValue(is, &(frame->fov), fov_context))==false) break;
		}
		if((flags & CUT_F_SAMECOLOR)==0 && flags & CUT_F_COLOR){
			frame->color=new bob_dom_frame::rgb();
			loadDoubleValue(is, &(frame->color->r), color_context);
			loadDoubleValue(is, &(frame->color->r), color_context);
			if((bRes=loadDoubleValue(is, &(frame->color->r), color_context))==false) break;
		}
		if((bRes=loadIntValue(is, &(frame->length), len_context))==false) break;
		if((bRes=loadIntValue(is, &(frame->index), idx_context))==false) break;
		
		break;
	}
	if(bRes){
		int c=0;
		while((t=is.tok()) && t->type!=token::t_closeBracket){
			c++;
			if(loadValue(is)==false) break;
		}
		if(t==NULL){
			error(is.previous(), S_Error, "Unexpected end of document found while looking for end of frame block '}'");
		}
		else if(c > 0){
			error(is.tok(), S_Warning, "Too many values in frame block: %d (expected %d), they will be discarded", frame->valueCount() + 2, frame->valueCount() + 2 + c);
		}
		++is; // past the end bracket
	}
	else{
		if(is.tok() && is.tok()->type==token::t_closeBracket)
			error(is.tok(), S_Error, "Premature end of frame block encountered. Expected %d values (+frame flags)", frame->valueCount() + 2);
	}
	return bRes;
}
#endif // !defined(X2BC_USE_INI_FORMATS)
//---------------------------------------------------------------------------------
bool bod_cut_parser::loadTCBInfo(token_stream& is, bob_dom_frame::tcb_info *info)
{
	if(!loadDoubleValue(is, &(info->tension), "TCB info (tension): ")) return false;
	if(!loadDoubleValue(is, &(info->continuity), "TCB info (continuity): ")) return false;
	if(!loadDoubleValue(is, &(info->bias), "TCB info (bias): ")) return false;
	if(!loadDoubleValue(is, &(info->easeFrom), "TCB info (ease from): ")) return false;
	if(!loadDoubleValue(is, &(info->easeTo), "TCB info (ease to): ")) return false;
	return true;
}
//---------------------------------------------------------------------------------