#include "ChatMessage.h"

#include "Globals.h"

ChatMessage::ChatMessage(char* data)
    : TextField(),
      lastWidth(0)
{
    setStyle(Style::VCenter | Style::Visible | Style::Multiline
             | Style::AutoLineBreak);
    setFontZ(dynamic_cast<Font*>(uiFactory.initParam.font->getThis()));
    setFontSize(12);
    setAutoLineBreakSpacing("    ");

    __int64 time = *(__int64*)data;
    short mLen = *(short*)(data + 8);
    char* message = new char[mLen + 1];
    memcpy(message, data + 10, mLen);
    message[mLen] = 0;
    char channelLen = *(data + 10 + mLen);
    char* channel = new char[channelLen + 1];
    memcpy(channel, data + 11 + mLen, channelLen);
    channel[channelLen] = 0;
    Framework::Text channelT = channel;
    delete[] channel;

    Time converter(time);
    Text* timeT = converter.getTime("d.m.y h:i:s");

    setFontColor(0xFFFFFFFF);
    if (channelT.isEqual("system:INFO"))
    {
        setFontColor(0xFFA0A0A0);
        channelT = "[INFO]";
    }
    else if (channelT.isEqual("system:WARNING"))
    {
        setFontColor(0xFFFF7700);
        channelT = "[WARNING]";
    }
    else if (channelT.isEqual("system:ERROR"))
    {
        setFontColor(0xFFFF0000);
        channelT = "[ERROR]";
    }
    else if (channelT.hasAt(0, "player:"))
    {
        Text* tmp = channelT.getTeilText(7);
        channelT = *tmp;
        tmp->release();
    }
    Text tmp = *timeT + " " + channelT + " " + message;
    tmp.replace("\n", "\n    ");
    setText(tmp);
    timeT->release();
    delete[] message;
}

bool ChatMessage::tick(double tickVal)
{
    if (getWidth() != lastWidth)
    {
        lastWidth = getWidth();
        setHeight(getNeededHeight());
    }
    return DrawableBackground::tick(tickVal);
}