#include <QPainter>
#include "grid.h"


GridEditor::GridEditor( QWidget *parent, const char *name )
    : QWidget( parent, name ), map(0)
{
}


GridEditor::~GridEditor()
{
}


void GridEditor::setMap( QRgb **m, int w, int h )
{
    gw = w;
    gh = h;
    map = m;
    cs = QMIN( width()/gw, height()/gh ) + 1;
    repaint(false);
}


void GridEditor::setColor( QRgb c )
{
    currColor = c;
}


void GridEditor::mousePressEvent( QMouseEvent *me )
{
    int x = me->pos().x()/cs;
    int y = me->pos().y()/cs;

    if ( x < gw && y < gh ) {
        if ( map[y][x] ) {
            map[y][x] = 0;
            clear = true;
        } else {
            map[y][x] = currColor;
            clear = false;
        }
        last = QPoint(x, y);
    }
    repaint(false);
    emit changed();
}


void GridEditor::mouseMoveEvent( QMouseEvent *me )
{
    int x = me->pos().x()/cs;
    int y = me->pos().y()/cs;

    if ( x < gw && y < gh && QPoint(x, y) != last) {
        if ( clear )
            map[y][x] = 0;
        else
            map[y][x] = currColor;
        last = QPoint(x, y);
    }
    repaint(false);
    emit changed();
}


void GridEditor::paintEvent( QPaintEvent *)
{
    QPainter painter(this);
    QPainter *p = &painter;
    if ( !map )
        return;
    for ( int y = 0; y < gh; y++ ) {
        for ( int x = 0; x < gw; x++ ) {
            p->fillRect(x*cs, y*cs, cs, cs, QColor(map[y][x]));
        }
    }
}

