#include "mapxwidget.h"

#include <QPainter>
#include <QMouseEvent>
#include <QDebug>

MapXWidget::MapXWidget(QWidget *parent)
    : QWidget(parent)
{
    mParent = parent;
    mPressed = false;
    m_svgobj.load(QString(":/images/worldmap_black.svg"));
    mPixmap.load(":/images/world_blue.jpg");
}

void MapXWidget::setViewpoint(QPointF p)
{
    mViewpoint = mapLayerPointToMapXPoint(p);
    update();
}

void MapXWidget::setViewArea(QPointF topLeft, QPointF bottomRight)
{
    QPointF p1, p2;
    p1 = mapLayerPointToMapXPoint(topLeft);
    p2 = mapLayerPointToMapXPoint(bottomRight);

    mViewArea = QRectF(p1, p2);
    // qDebug() << mViewArea;
}

void MapXWidget::paintEvent(QPaintEvent *e)
{
    QPainter p(this);
    // p.drawPixmap(this->rect(), mPixmap);
    QPixmap m_worldmap = QPixmap(this->rect().size());
    //m_worldmap.fill(Qt::transparent);
    m_worldmap.fill(QColor(153,154,146, 200));
    QPainter mapPainter;
    mapPainter.begin( &m_worldmap );
    mapPainter.setViewport( m_worldmap.rect() );
    m_svgobj.render( &mapPainter );
    mapPainter.end();
    p.drawPixmap( QPoint( 0, 0 ), m_worldmap );

    // 画外边框
    p.save();
    p.setPen(QPen(QColor("#4D4E4C"), 1.5));
    p.drawRect(this->rect());
    p.restore();

    // 画十字
    p.save();
    p.setPen(QPen(Qt::white, 1.0));
    p.setBrush(QBrush(Qt::white));

    QPointF p1;
    p1.setX(mViewpoint.x() - 4);
    p1.setY(mViewpoint.y() - 1);
    QRectF r1(p1, QSize(8, 2));

    QPointF p2;
    p2.setX(mViewpoint.x() - 1);
    p2.setY(mViewpoint.y() - 4);
    QRectF r2(p2, QSize(2, 8));

    p.drawRect(r1);
    p.drawRect(r2);

    p.drawPoint(mViewpoint);
    p.restore();

    // 画矩形
    p.save();
    p.setPen(QPen(Qt::white, 1.0));
    p.drawRect(mViewArea);
    p.restore();

    p.end();
}

void MapXWidget::mousePressEvent(QMouseEvent *e)
{
    mPressed = true;
    mLastPoint = e->pos();
}

void MapXWidget::mouseMoveEvent(QMouseEvent *e)
{
    if(mPressed)
    {
        if(mParent)
        {
            QPoint p = mapTo(mParent, e->pos());
            p = p - mLastPoint;
            if(p.x() >= 0 && p.x() <= mParent->width() - this->width()
                && p.y() >= 0 && p.y() <= mParent->height() - this->height())
                this->move(p);
        }
    }
}

void MapXWidget::mouseReleaseEvent(QMouseEvent *e)
{
    mPressed = false;
}

QPointF MapXWidget::mapLayerPointToMapXPoint(QPointF p)
{
    QPointF _p;
    _p.setX(p.x() * this->width() / 360.0);
    _p.setY(this->height() - p.y() * this->height() / 170.0);
    return _p;
}
