#include "CodeGenerator.h"
#include "ui_CodeGenerator.h"
#include "codebuilder/CodeBuilder.h"
#include "codebuilder/DefaultConfigs.h"
#include "UserConfiguration.h"
#include <QProperty>
#include <QTextStream>

class CodeGeneratorViewModel {
public:
    QProperty<QString> StructName;

private:

};

CodeGenerator::CodeGenerator(QWidget *parent)
	: QWidget(parent)
	, ui(new Ui::CodeGenerator)
    , Model(new CodeGeneratorViewModel)
{
	ui->setupUi(this);

	ui->generatedCodeEditor->setFont(UserConfiguration::instance()->codeFont());
	ui->generatedCodeEditor->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);


    auto v = Model->StructName.onValueChanged([this]() { ui->structNameEdit->setText(Model->StructName); });
}

CodeGenerator::~CodeGenerator()
{
    delete Model;
	delete ui;
}

void CodeGenerator::Init(std::shared_ptr<PgDatabaseCatalog> catalog, QString query,
						 std::shared_ptr<const Pgsql::Result> dbres)
{
	m_catalog = std::move(catalog);
	m_query = std::move(query);
	m_dbres = std::move(dbres);
	generateCode();
}

void CodeGenerator::on_updateCodeButton_clicked()
{
	generateCode();
}

void CodeGenerator::generateCode()
{
	QString struct_name = ui->structNameEdit->text();

	QString buffer;
	QTextStream stream(&buffer);
	CodeBuilder builder;
	builder.setLanguageConfig(getPglabCppLanguageConfig(m_catalog));
	builder.GenCodeForExecutingQuery(stream, m_query, *m_dbres, struct_name);
	stream.flush();
	ui->generatedCodeEditor->setPlainText(buffer);
//	QApplication::clipboard()->setText(buffer);

}
