#include "ChatHistory.h"

#include <Image.h>
#include <Scroll.h>

ChatHistory::ChatHistory()
    : Framework::DrawableBackground()
{
    setStyle(Style::Visible | Style::Allowed | Style::VScroll);
    setVerticalScrollPos(0);
    setMouseEvent(Framework::_ret1ME);
}

void ChatHistory::addMessage(ChatMessage* message)
{
    messages.add(message);
    scrollToBottom = 1;
}

void ChatHistory::render(Framework::Image& rObj)
{
    DrawableBackground::render(rObj);
    if (!rObj.setDrawOptions(innenPosition, innenSize)) return;
    rObj.addScrollOffset(
        horizontalScrollBar ? horizontalScrollBar->getScroll() : 0,
        vertikalScrollBar ? vertikalScrollBar->getScroll() : 0);
    for (ChatMessage* msg : messages)
        msg->render(rObj);
    rObj.releaseDrawOptions();
}

bool ChatHistory::tick(double tickVal)
{
    int y = 0;
    for (ChatMessage* msg : messages)
    {
        msg->setPosition(0, y);
        msg->setWidth(innenSize.x);
        rend |= msg->tick(tickVal);
        y += msg->getHeight();
    }
    vertikalScrollBar->update(y, innenSize.y);
    if (scrollToBottom)
    {
        setVerticalScrollPos(y);
        scrollToBottom = 0;
    }
    return DrawableBackground::tick(tickVal);
}