#include "factory/desktop/board_view.h"
#include <QGraphicsItem>
#include <QGraphicsScene>
#include <QMouseEvent>
#include <QPainter>
#include <QWheelEvent>
#include <algorithm>
#include <array>
#include <cmath>

namespace factory {
namespace {
constexpr int Cell = 36;
}
class BoardItem final : public QGraphicsItem {
public:
  Project project;
  Snapshot state;
  bool german{true};
  QRectF boundingRect() const override {
    return {0, 0, qreal(project.width * Cell), qreal(project.height * Cell)};
  }
  void updateBoard(const Project& next, const Snapshot& snapshot) {
    prepareGeometryChange();
    project = next;
    state = snapshot;
    update();
  }
  void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) override {
    constexpr std::array colors{"#f2f4f7", "#d7e0e9", "#273649", "#23856d", "#d6a043", "#7960ca"};
    constexpr std::array de{"", "", "", "E", "L", "A"};
    constexpr std::array en{"", "", "", "IN", "ST", "OUT"};
    painter->setRenderHint(QPainter::Antialiasing);
    QFont font = painter->font();
    font.setPixelSize(11);
    font.setBold(true);
    painter->setFont(font);
    for (int y = 0; y < project.height; ++y)
      for (int x = 0; x < project.width; ++x) {
        const auto tile = static_cast<std::size_t>(project.tile({x, y}));
        const QRectF rect(x * Cell + 1, y * Cell + 1, Cell - 2, Cell - 2);
        painter->setPen(Qt::NoPen);
        painter->setBrush(QColor(colors.at(tile)));
        painter->drawRoundedRect(rect, 4, 4);
        painter->setPen(Qt::white);
        painter->drawText(rect, Qt::AlignCenter, (german ? de : en).at(tile));
      }
    auto drawVehicle = [&](Position pos, int id) {
      QRectF rect(pos.x * Cell + 7, pos.y * Cell + 7, Cell - 14, Cell - 14);
      painter->setPen(QPen(QColor("#163c65"), 2));
      painter->setBrush(QColor("#4bace0"));
      painter->drawEllipse(rect);
      painter->setPen(QColor("#102a43"));
      painter->drawText(rect, Qt::AlignCenter, QString::number(id));
    };
    if (state.vehicles.empty())
      for (const auto& v : project.vehicles)
        drawVehicle(v.home, v.id);
    else
      for (const auto& v : state.vehicles)
        drawVehicle(v.position, v.spec.id);
  }
};
BoardView::BoardView(QWidget* parent) : QGraphicsView(parent) {
  auto* scene = new QGraphicsScene(this);
  setScene(scene);
  item_ = new BoardItem;
  scene->addItem(item_);
  setBackgroundBrush(QColor("#e9edf3"));
  setFrameShape(QFrame::NoFrame);
  setDragMode(QGraphicsView::ScrollHandDrag);
  setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
  setObjectName("board");
  setMinimumSize(320, 240);
  setAccessibleName("Warehouse map");
}
void BoardView::display(const Project& project, const Snapshot& snapshot) {
  item_->updateBoard(project, snapshot);
  scene()->setSceneRect(item_->boundingRect().adjusted(-12, -12, 12, 12));
}
void BoardView::fitBoard() { fitInView(sceneRect(), Qt::KeepAspectRatio); }
void BoardView::setGerman(bool german) {
  item_->german = german;
  item_->update();
}
void BoardView::paintCell(QMouseEvent* event) {
  const auto pos = mapToScene(event->position().toPoint());
  Position cell{static_cast<int>(std::floor(pos.x() / Cell)),
                static_cast<int>(std::floor(pos.y() / Cell))};
  if (cell == lastPainted_)
    return;
  lastPainted_ = cell;
  if (item_->project.contains(cell) && clicked)
    clicked(cell, event->buttons().testFlag(Qt::RightButton));
}
void BoardView::mousePressEvent(QMouseEvent* event) {
  lastPainted_ = {-1, -1};
  if (event->button() == Qt::MiddleButton || event->modifiers().testFlag(Qt::ControlModifier)) {
    QGraphicsView::mousePressEvent(event);
    return;
  }
  paintCell(event);
  event->accept();
}
void BoardView::mouseMoveEvent(QMouseEvent* event) {
  if (!event->modifiers().testFlag(Qt::ControlModifier) &&
      (event->buttons().testFlag(Qt::LeftButton) || event->buttons().testFlag(Qt::RightButton)))
    paintCell(event);
  else
    QGraphicsView::mouseMoveEvent(event);
}
void BoardView::wheelEvent(QWheelEvent* event) {
  const qreal factor = event->angleDelta().y() > 0 ? 1.15 : 1.0 / 1.15;
  const auto next = transform().m11() * factor;
  if (next > 0.12 && next < 4.0)
    scale(factor, factor);
  event->accept();
}
} // namespace factory
