#pragma once

#include "database.hh"
#include "../TradeCore/chart_candle.hh"
#include <QtWidgets/QGraphicsScene>
#include <QGraphicsRectItem>
#include <memory>

constexpr int defaultZoomFactor = 6;

/**
 * @brief Scene for graphics view to show currency exchange rate as candle chart
 */
class ChartScene : public QGraphicsScene
{
    Q_OBJECT

public:
    explicit ChartScene(QObject* parent = nullptr);
    virtual ~ChartScene() = default;
    void priceData(const QList<ChartCandle>& data);

    void orderEvents(
        const QList<EventRecord>& events,
        const QMap<int, QString>& eventTypes);

    void description(const QString& text);
    QList<ChartCandle> getSelection();
    bool hasSelection() const;
    void lineVisible(bool visible);
    bool lineVisible() const;
    void drawScene();
    void hideCursor(bool hidden);
    void zoomFactor(int zoom);
    int zoomFactor() const;

signals:
    void candleChanged(const ChartCandle& candle);
    void selectionChanged(int selectedCount);

private:
    void clearScene();
    void calcScale();
    void drawGrid();
    void drawTimeAxis();
    void drawData();
    void drawEvents();
    void drawDescription();
    void drawLine();
    void drawLevel(int x1, int x2, int y, QString text, bool textUnder);
    void drawMidLevel(int x1, int x2, int y, QString text);
    void drawCandle(int x, int width, int low, int high, int open, int close);
    void drawEvent(int x, int width, int price, int sl, int tp);
    void addToSelection(int index, int x);
    void removeFromSelection(int index);
    void mouseMoveEvent(QGraphicsSceneMouseEvent * mouseEvent);

private:
    QList<ChartCandle> data_;
    QList<EventRecord> events_;
    QMap<int, QString> eventTypes_;
    QString description_;
    double minPrice_;
    double maxPrice_;
    double scale_;
    bool lineVisible_;
    int zoom_;
    QPen gridPen_;
    QPen axisPen_;
    QPen bullishPen_;
    QPen bearishPen_;
    QPen stillPen_;
    QPen markerPen_;
    QPen selectionPen_;
    QPen priceLinePen_;
    QPen eventPricePen_;
    QPen eventLinePen_;
    QPen stopLossPen_;
    QPen takeProfitPen_;
    QBrush bullishBrush_;
    QBrush bearishBrush_;
    QBrush markerBrush_;
    QBrush selectionBrush_;
    QGraphicsRectItem* cursor_;
    QMap<int, QGraphicsRectItem*> selection_;
};
