#include "export.h"
#include <algorithm>
#include <render/render.h>
#include <resources.h>
#include <game/items.h>
#include <game/game.h>
#include <imgui/imgui.h>

namespace game{

exporter::exporter(const vec2u &pos, level *root):entity(pos, vec2u(2), root)
{
    _placeOnMap();
    _needShowGui = false;
    entity *e;
    for(cell *c: _cells)
        for(int i = 0; i < 4; i++)
            if(cell *s = c->sibling(i))
                if((e = s->get()) && e != this)
                    if(resourceProvider *p = dynamic_cast<resourceProvider*>(e))
                        _providers.push_back(p);

}

void exporter::onNeighbourCreated(entity *ent)
{
    std::lock_guard<std::mutex> lg(_locker);

    if(resourceProvider *p = dynamic_cast<resourceProvider*>(ent))
        if(std::find(_providers.begin(), _providers.end(), p) == _providers.end())
            _providers.push_back(p);
}

void exporter::beforeNeighbourDestroyed(entity *ent)
{
    std::lock_guard<std::mutex> lg(_locker);

    if(resourceProvider *r = dynamic_cast<resourceProvider*>(ent))
        _providers.remove(r);
}

void exporter::update()
{
    std::lock_guard<std::mutex> lg(_locker);

    for(resourceProvider *r:_providers)
        for(int i = 0; i < itemsCount(); i++)
            if(float rs = r->require(i,9999))
                addMoney(rs*getItemById(i)->price);
}

void exporter::draw()
{
    vec2u cursorDrawOffsets[4] = {vec2u(0),vec2u(1,0),vec2u(0,1),vec2u(1)};

    resources::atlas.draw(_pos, vec2u(0,10),vec2u(2));

    if(_needShowGui)
        for(int i = 0; i < 4; i++)
            resources::atlas.draw(_pos+cursorDrawOffsets[i],vec2u(i+1,14));
    else if(_needShowShortInfo)
        for(int i = 0; i < 4; i++)
            resources::atlas.draw(_pos+cursorDrawOffsets[i],vec2u(i+1,13));
}


void exporter::hover() noexcept
{
    _needShowShortInfo = true;
}

void exporter::select() noexcept
{
    _needShowGui = true;
    currentlyShown = this;
}

void exporter::onGui() noexcept
{
    _needShowShortInfo = false;
    if(!_needShowGui)
        return;

    if(currentlyShown != this)
    {
        _needShowGui = false;
        return;
    }

    ImGui::SetNextWindowSizeConstraints(ImVec2(256,160), ImVec2(256,800));
    if(ImGui::Begin(u8"Продажная фабрика", &_needShowGui, ImVec2(256,160)))
    {
        ImGui::PushStyleColor(ImGuiCol_Button, color::uint2rgba(0xe43b44));
        ImGui::PushStyleColor(ImGuiCol_ButtonHovered, color::uint2rgba(0xe43b44));
        ImGui::PushStyleColor(ImGuiCol_ButtonActive, color::uint2rgba(0xe43b44));

        if(ImGui::Button(u8"Сломать"))
            onCellDestroyed();

        ImGui::PopStyleColor(3);
    }
    else
    {
        if(!ImGui::IsWindowCollapsed())
            _needShowGui = false;
    }

    ImGui::End();
}


}
