#include "ItemList.h"

#include <FileSystem.h>
#include <Scroll.h>
#include <TextField.h>

#include "Game.h"
#include "Globals.h"
#include "UIMLToolTip.h"
#include "World.h"
#include <Globals.h>

ItemList::ItemList()
    : DrawableBackground(),
      currentTooltipSlot(-1)
{
    setStyle(DrawableBackground::Style::Visible
             | DrawableBackground::Style::Allowed);
    slotList = new int[itemTypeCount];
    memset(slotList, 0, sizeof(int) * itemTypeCount);
    slotCount = 0;
    setNeedToolTipEvent([this](Drawable* z, Point p) {
        int slot = getSlotByLocalPos(p);
        if (currentTooltipSlot != slot && currentTooltipSlot != -1)
        {
            std::cout << "closing tooltip\n";
            this->setToolTipZ(0);
            currentTooltipSlot = -1;
        }
        if (slot != -1)
        {
            std::cout << "requesting tooltip for slot " << slot << "\n";
            window->zScreen()->postAction([this, slot]() {
                UIMLToolTip* tip = new UIMLToolTip();
                tip->setUIML(itemTypes[slot]->getTooltipUIML());
                tip->setWarten(0);
                tip->setPosition(mausPos.x, mausPos.y + 15);
                setToolTipZ(tip);
            });
            currentTooltipSlot = slot;
            return 1;
        }
        return 0;
    });
}

ItemList::~ItemList()
{
    delete[] slotList;
}

int ItemList::getSlotByLocalPos(Framework::Point pos)
{
    int x = 0;
    int y = 0;
    for (int i = 0; i < slotCount; i++)
    {
        if (pos.x >= x && pos.x < x + 50 && pos.y >= y && pos.y < y + 50)
            return slotList[i];
        x += 60;
        if (x >= getWidth())
        {
            y += 60;
            x = 0;
        }
    }
    return -1;
}

void ItemList::doMouseEvent(Framework::MouseEvent& me, bool userRet)
{
    mausPos.x = me.originalX;
    mausPos.y = me.originalY;
    if (me.id == ME_Move)
    {
        if (getSlotByLocalPos(Point(me.mx, me.my)) != currentTooltipSlot)
        {
            if (currentTooltipSlot != -1)
            {
                std::cout << "closing tooltip\n";
                setToolTipZ(0);
            }
            else
                toolTipRequested = 0;
            currentTooltipSlot = -1;
        }
    }
    else if (me.id == ME_RLeft)
    {
        int pos = getSlotByLocalPos(Point(me.mx, me.my));
        if (pos >= 0)
        {
            World::INSTANCE->zClient()->craftingUIMLRequest(
                itemTypes[pos]->getId());
        }
    }
    else if (me.id == ME_RMiddle)
    {
        int pos = getSlotByLocalPos(Point(me.mx, me.my));
        if (pos >= 0)
        {
            if (Framework::getKeyState(T_Shift))
            {
                World::INSTANCE->zClient()->giveItemRequest(
                    itemTypes[pos]->getId(), 1);
            }
            else
            {
                World::INSTANCE->zClient()->giveItemRequest(
                    itemTypes[pos]->getId(), 0);
            }
        }
    }
    DrawableBackground::doMouseEvent(me, userRet);
}

bool ItemList::tick(double time)
{
    return DrawableBackground::tick(time);
}

void ItemList::adjustSize(int parentWidth, int parentHeight)
{
    int ipr = (parentWidth + 10) / 60;
    if (ipr == 0)
    {
        ipr = 1;
    }
    setSize(ipr * 60 - 10,
        (itemTypeCount / ipr + (itemTypeCount % ipr == 0 ? 0 : 1)) * 60 - 10);
}

void ItemList::render(Framework::Image& rObj)
{
    const Text* filter
        = dynamic_cast<Game*>((Menu*)menuRegister->get("game"))->zFilterText();
    DrawableBackground::render(rObj);
    if (!rObj.setDrawOptions(pos.x, pos.y, gr.x, gr.y)) return;
    int x = 0;
    int y = 0;
    int index = 0;
    for (int i = 0; i < itemTypeCount; i++)
    {
        if (filter->getLength() > 0
            && !itemTypes[i]->getName().has(filter->getText()))
        {
            continue;
        }
        slotList[index] = i;
        rObj.fillRegion(x, y, 50, 50, 0xFF222222);
        rObj.alphaImage(x, y, 50, 50, *itemTypes[i]->zIcon());
        x += 60;
        if (x >= getWidth())
        {
            x = 0;
            y += 60;
        }
        index++;
    }
    slotCount = index;
    rObj.releaseDrawOptions();
}

ItemListContainer::ItemListContainer()
    : Window()
{
    LTDBFile iconsDat;
    iconsDat.setFile(new Text("data/images/gui_icons.ltdb"));
    iconsDat.readData(0);

    setStyle(Window::Style::Allowed | Window::Style::Border
             | Window::Style::BodyBAlpha | Window::Style::Movable
             | Window::Style::Title | Window::Style::TitleBAlpha
             | Window::Style::TitleBackground | Window::Style::BodyBackground
             | Window::Style::MEIgnoreInside | Window::Style::VScroll
             | Window::Style::WidthChangeable | Window::Style::BodyMinWidth
             | Window::Style::BodyMinHeight | Window::Style::HeightChangeable
             | Window::Style::Closable | Window::Style::ClosingBAlpha
             | Window::Style::ClosingBuffer | Window::Style::ClosingBAlpha
             | Window::Style::ClosingBackground | Style::ClosingBImage
             | Style::ClosingBuffer);
    setBodyBgColor(0xA0000000);
    setTBgColor(0xA0000000);
    setCloseBgColor(0xA0000000);
    setSize(329, window->zScreen()->getBackBufferSize().y - 20);
    setPosition(window->zScreen()->getBackBufferSize().x - getWidth() - 10, 10);
    setBorderWidth(2);
    setBorderColor(0xFF52525E);
    setTitel("Recipies");
    setTFontZ(dynamic_cast<Font*>(uiFactory.initParam.font->getThis()));
    zTTextField()->setSize(0, 20);
    zTTextField()->addStyle(TextField::Style::Center);
    setKeyboardEvent(_ret1TE);
    setBodyMin(70, 70);
    setVSBScroll(0);
    zVScrollBar()->setBgColor(0xA0000000, 1);
    setClosingMe([this](void* p, void* o, MouseEvent me) {
        if (me.id == ME_RLeft) removeStyle(Style::Visible);
        return 1;
    });
    setCloseAfStrength(10);
    setCloseAfColor(0x5F9C0A0A);
    setCloseBgImageZ(iconsDat.load(0, new Text("close.png")));
    setCloseClickAfColor(0xFF9C0A0A);
    setCloseClickAfStrength(10);

    list = new ItemList();
    list->setPosition(10, 10);
    addMember(list);
}

bool ItemListContainer::tick(double time)
{
    list->adjustSize(getInnerWidth() - 35, getInnerHeight());
    if (zVScrollBar()->getScrollData()->max != list->getHeight() + 20)
        setVSBMax(list->getHeight() + 20);
    return Window::tick(time);
}