#include "scroller.h"

cCcScroller::cCcScroller(){
	crtLine = 0;
	lines[crtLine] = NULL;
	SetWindow(32,3);
}

cCcScroller::~cCcScroller(){
	for(int i=0; i<crtLine; i++)
		if(lines[i]!=NULL)
			delete [] lines[i];
}

bool cCcScroller::SetWindow(int width, int height){
	text_width = width;
	text_height = height;
	
	return true;
}
bool cCcScroller::AddText(char *text){
	return AddText(text, strlen(text));
}

bool cCcScroller::AddText(char *text, int length){
	dprint(1, "Adding text[%d]: %s ... \n", length, text);
	int len = length;
	int size = len;
	int pos = 0;
		
	if(lines[crtLine]==NULL)
		AddNewLine(NULL);
	pos = strlen(lines[crtLine]);
	
	if((len + pos) >= text_width)
		size = text_width - pos;
	
	dprint(1, "Lines: %d\tCrt size: %d\tNew text size: %d Copy size: %d\n", crtLine, pos, len, size);
	strncpy(lines[crtLine] + pos, text, size);
	lines[crtLine][pos+size] = 0x00;
	
	if(size!=len && size)
		AddNewLine(text + size);	
	
	return true;
}

bool cCcScroller::AddNewLine(char *text){
	dprint(1, "Adding new line: %s ... \n", text==NULL ? "[NULL]" : text);
	if(lines[crtLine]!=NULL)
		if(strlen(lines[crtLine])>0)
			Scroll();
	lines[crtLine] = new char[text_width];
	lines[crtLine][0] = 0x00;
	lines[crtLine][text_width] = 0x00;
	if(text!=NULL)
		return AddText(text);
	return true;
}

bool cCcScroller::Clear(void){
	dprint(1, "[Clear Scroller Buffer]");
	for(int i=0; i<crtLine; i++){
		delete [] lines[i];
		lines[i] = NULL;
	}
		
	crtLine = 0;
	return true;
}

bool cCcScroller::Backspace(void){
	//int lastPos;
	if(lines[crtLine]==NULL)
		if(crtLine>0)
			crtLine--;
	
		
	if(lines[crtLine]!=NULL)
		if(strlen(lines[crtLine])>0)
			lines[crtLine][strlen(lines[crtLine]) - 1] = 0x00;
	
	return true;
}

bool cCcScroller::TabOffset(int offset){ // 0 < offset < 3
	for(int i=0; i< offset; i++)
		AddText(" ");
		
	return true;
}

bool cCcScroller::DelEndLine(void){
	return true;
}

char **cCcScroller::GetLines(void){
	return lines;
}

int cCcScroller::CountLines(void){
	return crtLine+1;
}

bool cCcScroller::Scroll(int num_lines){
	dprint(1, "Scrolling %d lines out of %d...\n", num_lines, text_height);
	while(num_lines-->0){
		if(crtLine == text_height-1){
			delete [] lines[0];
			for(int line=0; line < crtLine; line++)
				lines[line] = lines[line+1];
			}
		else
			crtLine++;
		lines[crtLine] = NULL;
	}
	return true;
}


bool cCcScroller::WrapText(char *text, int width){
	return true;
}
