#include "scroll.h"

cCharScroll::cCharScroll(void) {
    asprintf(&Text, " ");
    bmp = NULL;
    Font = cFont::GetFont(fontOsd);
    DestWidth = 0;
    ColorDepth = 1;
    Bg = 0xFF000000;
    Fg = 0xFFFFFFFF;
    xOff = 0;
    yOff = 0;
    delay = 20;
    intervall = 20;
    }
    
cCharScroll::~cCharScroll() {
    if (Text)
	free(Text);
    if (bmp)
	delete(bmp);
    }

bool cCharScroll::SetText(const char *text, int textnumber) {
    if (Text)
	free(Text);
    asprintf(&Text, "%s", (text || !isempty(text))? text : " ");
    if (!DestWidth || !SkinElchiSetup.scrolling)
	return false;
    int width = Font->Width(Text);
    if (width > DestWidth) {
	int height = Font->Height();
	width += 2 * Font->Width(" ");
	if (bmp)
    	    bmp->SetSize(width, height);
	else
	    bmp = new cBitmap(width, height, ColorDepth);
	char *s;
	asprintf(&s, " %s ", Text);
	bmp->DrawText(0, 0, s, Fg, Bg, Font);
	free(s);
	Delay = delay;
	return true;
	}
    return false;
    }

bool cCharScroll::DrawNeeded(void) {
if (bmp) {
    int elapsed = ((int)Time.Elapsed()) / intervall;
    if (elapsed) {
	if (Delay > 0) {
	    int x = elapsed / Delay;
	    Delay -= elapsed;
	    if (Delay <= 0)
	        pos -= dir * x;
	    else {
		Time.Set();
	        return false;
		}
	    }
	else
	    pos = pos - (dir * elapsed);
	if (pos < 0) {
	    pos = 0;
	    dir = -1;
	    }
	else {
	    int x = Width() - DestWidth;
	    if (pos > x) {
	    	pos = x;
	    	dir = 1;
		}
	    }
	int x = Width() - DestWidth - pos;
	Delay = delay - ((x > pos) ? pos : x);
	Time.Set();
        return true;
        }
    }
    return false;
}
