#include "event_widget.hh"
#include "../TradeCore/functions.hh"
#include <QDebug>
#include <QRgb>
#include <memory>

namespace {

constexpr char dateTimeFormat[] = "dd.MM.yyyy HH:mm";
constexpr int columnSpace = 15;
constexpr QRgb profitColor = qRgb(0, 120, 0);
constexpr QRgb lossColor = qRgb(140, 0, 0);

void appendRow(
    EventWidget& widget, const EventRecord& record,
    const QMap<int, QString>& eventTypes, int digits)
{
    int row = widget.rowCount();
    widget.insertRow(row);

    widget.setItem(row, 0, new QTableWidgetItem(
        eventTypes.value(record.event, QTableWidget::tr("Unknown"))));

    widget.setItem(row, 1, new QTableWidgetItem(
        QString::number(record.ticket)));

    widget.setItem(row, 2, new QTableWidgetItem(QString::number(record.lots)));

    QBrush profitForeground =
        record.profit < 0 ? QBrush(lossColor): QBrush(profitColor);

    auto profitItem = std::make_unique<QTableWidgetItem>();
    profitItem->setText(QString::number(record.profit));
    profitItem->setForeground(profitForeground);
    widget.setItem(row, 3, profitItem.release());

    auto profitPipsItem = std::make_unique<QTableWidgetItem>();
    profitPipsItem->setText(QString::number(
        abs((record.openPrice - record.closePrice) * pow(10, digits))
        * (record.profit < 0 ? -1 : 1)));
    profitPipsItem->setForeground(profitForeground);
    widget.setItem(row, 4, profitPipsItem.release());

    widget.setItem(row, 5, new QTableWidgetItem(
        QString::number(record.openPrice)));

    widget.setItem(row, 6, new QTableWidgetItem(
        QString::number(record.closePrice)));

    widget.setItem(row, 7, new QTableWidgetItem(
        QString::number(record.stopLoss)));

    widget.setItem(row, 8, new QTableWidgetItem(
        QString::number(record.takeProfit)));

    widget.setItem(row, 9, new QTableWidgetItem(
        record.time.toString(dateTimeFormat)));
}

} //namespace


EventWidget::EventWidget(QWidget* parent) :
    QTableWidget(parent)
{}

EventWidget::~EventWidget()
{}

void EventWidget::displayEvents(
    const QList<EventRecord>& events,
    const QMap<int, QString>& eventTypes, int digits)
{
    setRowCount(0);

    for (auto& record : events)
        appendRow(*this, record, eventTypes, digits);

    resizeColumnsToContents();

    for(int i = 0; i < columnCount(); i++)
        setColumnWidth(i, columnWidth(i) + columnSpace);
}
