#include "order_widget.hh"
#include <memory>
#include <QDebug>

namespace {

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

void appendRow(
    OrderWidget& widget,
    const OrderRecord& record,
    const QMap<int, QString>& currencies,
    const QMap<int, QString>& timeFrames)
{
    int row = widget.rowCount();
    widget.insertRow(row);

    auto idItem = std::make_unique<QTableWidgetItem>();
    idItem->setText(QString::number(record.id));
    idItem->setData(Qt::UserRole, record.id);
    widget.setItem(row, 0, idItem.release());

    auto digitsItem = std::make_unique<QTableWidgetItem>();
    digitsItem->setText(QString::number(record.digits));
    digitsItem->setData(Qt::UserRole, record.digits);
    widget.setItem(row, 1, digitsItem.release());

    widget.setItem(row, 2, new QTableWidgetItem(QString::number(record.client)));
    widget.setItem(row, 3, new QTableWidgetItem(record.strategy));

    widget.setItem(row, 4, new QTableWidgetItem(
        currencies.value(record.currency, QTableWidget::tr("Unknown"))));

    widget.setItem(row, 5, new QTableWidgetItem(
        timeFrames.value(record.timeFrame, QTableWidget::tr("Unknown"))));

    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, 6, profitItem.release());

    widget.setItem(row, 7, new QTableWidgetItem(
        record.created.toString(dateTimeFormat)));
}

} //namespace

OrderWidget::OrderWidget(QWidget* parent) :
    QTableWidget(parent)
{
    setColumnCount(8);
    setColumnHidden(0, true);
    setColumnHidden(1, true);

    setHorizontalHeaderItem(0, new QTableWidgetItem(tr("Id")));
    setHorizontalHeaderItem(1, new QTableWidgetItem(tr("Digits")));
    setHorizontalHeaderItem(2, new QTableWidgetItem(tr("Expert")));
    setHorizontalHeaderItem(3, new QTableWidgetItem(tr("Strategy")));
    setHorizontalHeaderItem(4, new QTableWidgetItem(tr("Currency")));
    setHorizontalHeaderItem(5, new QTableWidgetItem(tr("Period")));
    setHorizontalHeaderItem(6, new QTableWidgetItem(tr("Profit")));
    setHorizontalHeaderItem(7, new QTableWidgetItem(tr("Logged")));
}

OrderWidget::~OrderWidget()
{}

void OrderWidget::displayOrders(
    const QList<OrderRecord>& orders,
    const QMap<int, QString>& currencies,
    const QMap<int, QString>& timeFrames)
{
    setRowCount(0);

    for (auto& record : orders)
        appendRow(*this, record, currencies, timeFrames);

   resizeColumnsToContents();

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