#include "piece.h"

#include <math.h>

#include <qpainter.h>
#include <qbitmap.h>

#include "base/board.h"


const FEPieceInfo::Form FEPieceInfo::FORM = {
	{{ 0,  0}, {-1,  0}, { 0,  0}, { 0, -1}},
    {{ 0, -1}, {-1, -1}, {-1,  0}, {-1, -1}}
};

const QColor FEPieceInfo::COLORS[NB_NORM_BLOCK_TYPES + 1] = {
    // normal
	QColor(100, 200, 100),
	QColor(100, 200, 200),
	QColor(200, 100, 100),
	QColor(200, 100, 200),
    // garbage
	QColor(200, 200, 200) // light gray
};

void FEPieceInfo::draw(QPixmap *pixmap, uint blockType, uint, bool lighted) const
{
    QColor color = COLORS[blockType];
    if (lighted) color = color.light();
    pixmap->fill(color);
}

void FEPieceInfo::setMask(QPixmap *pixmap, uint blockMode) const
{
    Q_ASSERT( pixmap->width()==pixmap->height() ); // drawing code assumes that
    QBitmap bitmap(pixmap->size(), true);
    QPainter p(&bitmap);
	p.setBrush(Qt::color1);
	p.setPen( QPen(Qt::NoPen) );

	// base circle
    int w = pixmap->width();
	int d = (int)((sqrt(2)-2./3)*w);
	QRect cr = QRect(0, 0, d, d);
	cr.moveCenter(QPoint(w/2, w/2));
	p.drawEllipse(cr);

	if (blockMode) {
        int a  = (int)(w/(3.*sqrt(2)));
        int ra = 2*w/3+1;
        cr = QRect(0, 0, ra, ra);

        // first drawing with color1
        if ( blockMode & BaseBoard::Up    ) p.drawRect(    0,     0, w, a);
        if ( blockMode & BaseBoard::Right ) p.drawRect(w-a+1,     0, a, w);
        if ( blockMode & BaseBoard::Down  ) p.drawRect(    0, w-a+1, w, a);
        if ( blockMode & BaseBoard::Left  ) p.drawRect(    0,     0, a, w);

        // second drawing with color0
        p.setBrush(Qt::color0);
        if ( (blockMode & BaseBoard::Up) || (blockMode & BaseBoard::Left) ) {
            cr.moveCenter(QPoint(0, 0));
            p.drawEllipse(cr);
        }
        if ( (blockMode & BaseBoard::Right) || (blockMode & BaseBoard::Up) ) {
            cr.moveCenter(QPoint(w-1, 0));
            p.drawEllipse(cr);
        }
        if ( (blockMode & BaseBoard::Down) || (blockMode & BaseBoard::Right) ){
            cr.moveCenter(QPoint(w-1, w-1));
            p.drawEllipse(cr);
        }
        if ( (blockMode & BaseBoard::Left) || (blockMode & BaseBoard::Down) ) {
            cr.moveCenter(QPoint(0, w-1));
            p.drawEllipse(cr);
        }
    }

    p.end();
    pixmap->setMask(bitmap);
}
