
#include "mob_solid.hh"

#include "itty/paths.hh"

#include "mob_player.hh"
#include "scene.hh"
#include "strings.hh"


//////////////////////////////////////////////////////////////////////////////
/// Mob_mirror
//////////////////////////////////////////////////////////////////////////////

Mob_mirror::Mob_mirror(Mobs& mobs, const itty::Box& box, Place* place) : Mob{box, 0}, place_{place}
{
}

bool Mob_mirror::update(Scene& sc)
{
        if (!box.overlaps(sc.mobs.pc->hit))
                return false;

        auto my_target = [this](auto&& p){ return p.type == "target" && p.name == place_->name; };
        auto i = std::find_if(sc.places.begin(), sc.places.end(), my_target);
        if (i == sc.places.end()) {
                log_err("Can't find the target for this mirror");
                return false;
        }

        sc.mobs.pc->p = i->box.ct();
        return false;
}

void Mob_mirror::render(Mobs& mobs)
{
}

//////////////////////////////////////////////////////////////////////////////
/// Mob_crack
//////////////////////////////////////////////////////////////////////////////

Mob_crack::Mob_crack(Mobs& mobs, const itty::Box& box, Place* place) : Mob{box, 0}, place_{place}
{
        sound_kill = mobs.load_audio("kill.wav");
}

bool Mob_crack::update(Scene& sc)
{
        if (!box.overlaps(sc.mobs.pc->hit))
                return false;

        auto my_brush = [this](auto&& p){ return p.type == "brush" && p.name == place_->name; };
        auto i = std::find_if(sc.places.begin(), sc.places.end(), my_brush);
        if (i == sc.places.end()) {
                log_err("Can't find the brush for this crack");
                return false;
        }

        MIX_PlayAudio(itty::mixer, sound_kill);
        int x0 = floor(box.l / 8);
        int x1 = floor(i->box.l / 8);
        int w = ceil(box.r / 8) - x0;
        int y0 = floor(box.u / 8);
        int y1 = floor(i->box.u / 8);
        int h = ceil(box.d / 8) - y0;
        for (int x = 0; x != w; ++x)
                for (int y = 0; y != h; ++y) {
                        std::swap(sc.bkgr.at(x0 + x, y0 + y), sc.bkgr.at(x1 + x, y1 + y));
                        std::swap(sc.phys.at(x0 + x, y0 + y), sc.phys.at(x1 + x, y1 + y));
                }
        sc.bkgr.upload(sc.room);
        place_->box = itty::Box{INFINITY, INFINITY, INFINITY, INFINITY};
        return true;
}

void Mob_crack::render(Mobs& mobs)
{
}

