#include "tuplesresultwidget.h"
#include "ui_tuplesresultwidget.h"
#include "ResultTableModelUtil.h"
#include "util.h"

#include <QFile>
#include <QTextStream>
#include "util/PgLabItemDelegate.h"


TuplesResultWidget::TuplesResultWidget(QWidget *parent) :
	QWidget(parent),
	ui(new Ui::TuplesResultWidget)
{
	ui->setupUi(this);
	ui->lblRowCount->setText(QString());

	SetTableViewDefault(ui->ResultView);
	auto delegate = new PgLabItemDelegate(ui->ResultView);
	ui->ResultView->setItemDelegate(delegate);
}

TuplesResultWidget::~TuplesResultWidget()
{
	delete ui;
}

void TuplesResultWidget::setResult(std::shared_ptr<QueryResultModel> res, float ms)
{
	resultModel = res;
	ui->ResultView->setModel(resultModel.get());

	ui->ResultView->resizeColumnsToContents();

	QString rowcount_str = QString("rows: %1").arg(resultModel->rowCount());
	ui->lblRowCount->setText(rowcount_str);
	ui->lblElapsedTime->setText(msfloatToHumanReadableString(ms));
}

void TuplesResultWidget::exportData(const QString &file_name) const
{
	QFile file(file_name);
	if (file.open(QIODevice::WriteOnly)) {
		QTextStream out(&file);
		::exportTable(ui->ResultView, out);
	}
}


