//:vp.cc

#include <math.h>
#include "vp.h"


vp::vp(const char* fname, fm* tfmP, sb* tsbP, int w, int ht) :
    Fl_Window(w,ht,fname),
    mlo(0, 0, w, ht, 0),
    fontSize(16),
    fmP(tfmP),
    sbP(tsbP),
    numVisibleItems( ht / fontSize )
{
    mlo.color(FL_WHITE);
    resizable(mlo);
    sbP->setNumVisibleItems(numVisibleItems);
    end();
    show();
}


void
vp::draw() {
    draw_box(box(), x(), y(), w(), h(), color());
    setContents();
    mlo.value(contents.c_str());
    Fl_Window::draw();
}


extern void sbtweak();
extern void dltweak();

void
vp::resize(int x, int y, int w, int ht) {
//  h()-Fl::box_dh(b)
//  y()+Fl::box_dy(b)
    cout << "resize" << endl;
    Fl_Window::resize(x, y, w, ht);
    cout << "\tht: " << ht << endl;
    cout << "\tfontSize: " << fontSize << endl;
    numVisibleItems = ht / fontSize;
    sbP->setNumVisibleItems(numVisibleItems);

    cout << "\tnumVisibleItems: " << numVisibleItems << endl;
    cout << "\tfmP->fileSize: " << fmP->fileSize << endl;
    int topLine = fmP->fileSize - numVisibleItems;
    cout << "\ttopLine: " << topLine << endl;
    cout << "\tsbP->position: " << sbP->position << endl;
    if (sbP->position > topLine)
        sbP->setPosition(topLine);

    sbtweak();
    dltweak();
}


void
vp::setContents() {

    int topLine = sbP->position;
    int totalLines = min(fmP->fileSize, numVisibleItems);
    int bottomLine = topLine + totalLines - 1;

    string st;
    for (int i = topLine; i <= bottomLine; i++)
        st += fmP->getLine(i);
    contents = st;
}


void
vp::update() {
    mlo.damage(FL_DAMAGE_SCROLL);
}
