#include "textprinterwindow.h"
#include "ui_textprinterwindow.h"

#include <QFileDialog>

#include "aspeqtsettings.h"

TextPrinterWindow::TextPrinterWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::TextPrinterWindow)
{
    ui->setupUi(this);
    QFont f;
    f.setFixedPitch(true);
    f.setFamily("monospace");
    ui->printerTextEdit->setFont(f);
}

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

void TextPrinterWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void TextPrinterWindow::closeEvent(QCloseEvent *e)
{
    emit closed();
    e->accept();
}

void TextPrinterWindow::print(const QString &text)
{
    QTextCursor c = ui->printerTextEdit->textCursor();
    c.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
    ui->printerTextEdit->setTextCursor(c);
    ui->printerTextEdit->insertPlainText(text);
}

void TextPrinterWindow::on_actionWord_wrap_triggered()
{
    if (ui->actionWord_wrap->isChecked()) {
        ui->printerTextEdit->setLineWrapMode(QPlainTextEdit::WidgetWidth);
    } else {
        ui->printerTextEdit->setLineWrapMode(QPlainTextEdit::NoWrap);
    }
}

void TextPrinterWindow::on_actionClear_triggered()
{
    ui->printerTextEdit->clear();
}

void TextPrinterWindow::on_actionSave_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save printer text output"), aspeqtSettings->lastPrinterTextDir(),
                                                    tr("Text files (*.txt);;All files (*)"), 0);
    if (fileName.isEmpty()) {
        return;
    }
    aspeqtSettings->setLastPrinterTextDir(QFileInfo(fileName).absolutePath());
    QFile file(fileName);
    file.open(QFile::WriteOnly | QFile::Truncate | QFile::Text);
    file.write(ui->printerTextEdit->toPlainText().toLatin1());
}
