#include "ItemStack.h"

#include <XML.h>

#include "Globals.h"
#include "UIMLToolTip.h"

ItemStackElement::ItemStackElement()
    : Framework::UIMLElement()
{}

bool ItemStackElement::isApplicableFor(Framework::XML::Element& element)
{
    return element.getName().isEqual("itemStack");
}

Framework::Drawable* ItemStackElement::parseElement(
    Framework::XML::Element& element, Framework::UIMLContainer& generalFactory)
{
    ItemStackView* result = new ItemStackView(dynamic_cast<Framework::Font*>(
        generalFactory.getFactory().initParam.font->getThis()));
    updateElement(element, *result, generalFactory);
    return result;
}

bool ItemStackElement::updateElement(Framework::XML::Element& element,
    Framework::Drawable& z,
    Framework::UIMLContainer& generalFactory)
{
    ItemStackView* view = dynamic_cast<ItemStackView*>(&z);
    if (!view) return false;
    view->setCount(element.getAttributeValue("count"));
    auto tip = element.selectChildsByName("tip");
    if (tip.exists())
    {
        view->setToolTip((Framework::RCPointer<Framework::XML::Element>)
                tip.getFirstElement());
    }
    int type = (int)element.getAttributeValue("type");
    const ItemType* itemType = zItemType(type);
    if (itemType)
    {
        view->setBackgroundImageZ(
            dynamic_cast<Framework::Image*>(itemType->zIcon()->getThis()));
    }
    return true;
}

ItemStackView::ItemStackView(Framework::Font* font)
    : Framework::DrawableBackground(),
      count("")
{
    setStyle(
        DrawableBackground::Style::Allowed | DrawableBackground::Style::Visible
        | DrawableBackground::Style::Background
        | DrawableBackground::Style::BImage | DrawableBackground::Style::BAlpha
        | DrawableBackground::Style::Border);
    setBorderWidth(1);
    setBorderColor(0xFF52525E);
    tr.setFontZ(font);
    tr.setFontSize(12);
}

void ItemStackView::setCount(Framework::Text count)
{
    this->count = count;
}

void ItemStackView::setToolTip(Framework::XML::Element* zToolTipUIML)
{
    UIMLToolTip* tip = new UIMLToolTip();
    tip->setUIML(zToolTipUIML->toString());
    setToolTipZ(tip);
}

void ItemStackView::render(Framework::Image& rObj)
{
    Framework::DrawableBackground::render(rObj);
    if (rObj.setDrawOptions(pos, gr))
    {
        if (rObj.setDrawOptions(getBorderWidth(),
                getBorderWidth(),
                getInnerWidth(),
                getInnerHeight()))
        {
            tr.renderText(getInnerWidth() - 5 - tr.getTextWidth(count),
                getInnerHeight() - 5 - tr.getTextHeight(count),
                count,
                rObj,
                0xFFFFFFFF);
            rObj.releaseDrawOptions();
        }
        rObj.releaseDrawOptions();
    }
}