#include "tilemap.h"
#include "japi/draw.h"
#include <stdint.h>

namespace tilemap
{
    uint16_t tiles[16*32];
    uint32_t back_color = 0xff000000;
    uint32_t border_color = 0xff000000;
    SDL_Texture *tileset;
    SDL_Texture *map;
    uint32_t paleta[16] = {
        0xff000000, 0xff3c351f, 0xff0000d8, 0xff0000ff, 0xffd80000, 0xffff0000,
        0xffd800d8, 0xffff00ff, 0xff00d800, 0xff00ff00, 0xff00d8d8, 0xff00ffff,
        0xffd8d800, 0xffffff00, 0xffd8d8d8, 0xffffffff
    };

    void init()
    {
        tileset = draw::loadSurface("tilesets/standard.gif", 16);
        map = draw::createSurface(32*8, 16*8);
    }

    void start()
    {
        draw::setClip(200,48,draw::getWindowSize().x-400, draw::getWindowSize().y-48);
        draw::setColor(border_color);
        draw::fillrect(200,48,draw::getWindowSize().x-400, draw::getWindowSize().y-48);
    }

    void draw()
    {
        const int width = draw::getWindowSize().x-400;
        const int height = (128*width)/256;
        const int x = 200;
        const int y = ((draw::getWindowSize().y-48)-height)/2;
        draw::setSource(map);
        draw::draw({0,0,256,128},{x,y,width,height});
    }

    void end()
    {
        draw::resetClip();
    }

    void rebuild()
    {
        draw::setDestination(map);
        draw::setSource(tileset);
        draw::cls(back_color);
        int i=0;
        for (int y=0; y<16; ++y) {
            for (int x=0; x<32; ++x) {
                draw::draw({(tiles[i]%24)*8, (tiles[i]/24)*8, 8, 8}, {x*8, y*8, 8, 8});
                i++;
            }
        }
        draw::setDestination(nullptr);
    }

    void set(uint16_t *tiles)
    {
        memcpy(tilemap::tiles, tiles, 32*16*2);
        rebuild();
    }

    void setBackground(int color)
    {
        back_color = paleta[color];
        rebuild();
    }

    void setBorder(int color)
    {
        border_color = paleta[color];
        rebuild();
    }

}
