#include "tab_docs.h"
#include <QtWidgets>
#include <QtXml>


tabDoc::tabDoc(QWidget* p_parent) : QPlainTextEdit(p_parent),
  directory(""),
  flag(false)
{
    connect(this, &tabDoc::textChanged, this, &tabDoc::sltDocChanged);

    lineNumberArea = new LineNumberArea(this);

    connect(this, &tabDoc::blockCountChanged, this, &tabDoc::updateLineNumberAreaWidth);
    connect(this, &tabDoc::updateRequest, this, &tabDoc::updateLineNumberArea);
    connect(this, &tabDoc::cursorPositionChanged, this, &tabDoc::highlightCurrentLine);

    updateLineNumberAreaWidth(0);

    lineNumberArea->hide();
}


QString tabDoc::sltLoad()
{
    directory = QFileDialog::getOpenFileName();

    if (directory.isEmpty())
        return "";

    return sltLoad(directory);
}

void tabDoc::linesHelp()
{
    lineNumberArea->show();
}

QString tabDoc::sltLoad(const QString& p_fDirectory)
{
    directory = p_fDirectory;
    QStringList list = p_fDirectory.split("/");
    name_ = list.last();

    list.clear();

    list = name_.split(".");
    ext_ = list.last();

    QFile file(p_fDirectory);

    if (file.open(QIODevice::ReadOnly))
    {
        QTextStream stream(&file);

        disconnect(this, &tabDoc::textChanged, this, &tabDoc::sltDocChanged);
        setPlainText(stream.readAll());
        connect(this, &tabDoc::textChanged, this, &tabDoc::sltDocChanged);

        qDebug() << name_;
        emit changeWidTitle("", "");

        return name_;
    }
    lineNumberArea->show();
    return "";
}

void tabDoc::sltIsCodeDoc()
{
    lineNumberArea->show();
    highlightCurrentLine();

    sltLoadHighlight();
}

void tabDoc::sltSave()
{
    if (directory.isEmpty())
    {
        sltSaveAs(name_);
        return;
    }

    QFile file(directory);
    if(file.open(QIODevice::WriteOnly))
    {
        QTextStream(&file) << toPlainText();
        file.close();

        connect(this, &tabDoc::textChanged, this, &tabDoc::sltDocChanged);

        emit changeWidTitle("", "");
    }

    flag = false;
}

void tabDoc::sltSaveAs(const QString& p_tip)
{
    QString newFileName = QFileDialog::getSaveFileName(0, directory, p_tip);
    if (!newFileName.isEmpty())
    {
        QString lastFileName = name_;
        QString lastFileDirectory = directory;

        directory = newFileName;
        QStringList list = directory.split("/");
        name_ = list.last();

        list.clear();

        list = name_.split(".");
        ext_ = list.last();
        emit changeWidTitle(lastFileName, lastFileDirectory);
        sltSave();
    }
}

void tabDoc::sltLoadHighlight()
{
    selector = new Lighter_class(this->document(), ext_);
    QString f_styleFName = ":/hLIni/highlightTest.xml";

    QFile styleFile(f_styleFName);
    QXmlInputSource src(&styleFile);
    QXmlSimpleReader reader;

    reader.setContentHandler(selector);

    qDebug() << "Ready to parse...";
    reader.parse(src);

}

void tabDoc::sltDocChanged()
{
    qDebug() << "Doc " << directory << " changed!";
    flag = true;
    disconnect(this, &tabDoc::textChanged, this, &tabDoc::sltDocChanged);
    emit fileChanded(name_);
}


void tabDoc::sltSetChanged(bool p_was)
{
    flag = p_was;
}


int tabDoc::lineNumberAreaWidth()
{
    int digits = 1;
    int max = qMax(1, blockCount());
    while (max >= 10) {
        max /= 10;
        ++digits;
    }

    int space = 3 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;

    return space;
}



void tabDoc::updateLineNumberAreaWidth(int)
{
    setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}


void tabDoc::updateLineNumberArea(const QRect &rect, int dy)
{
    if (dy)
        lineNumberArea->scroll(0, dy);
    else
        lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());

    if (rect.contains(viewport()->rect()))
        updateLineNumberAreaWidth(0);
}

void tabDoc::resizeEvent(QResizeEvent *e)
{
    QPlainTextEdit::resizeEvent(e);

    QRect cr = contentsRect();
    lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}

void tabDoc::highlightCurrentLine()
{
    QList<QTextEdit::ExtraSelection> extraSelections;

    if (!isReadOnly())
    {
        QTextEdit::ExtraSelection selection;

        QColor lineColor = QColor(Qt::yellow).lighter(160);

        selection.format.setBackground(lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = textCursor();
        selection.cursor.clearSelection();
        extraSelections.append(selection);
    }

    setExtraSelections(extraSelections);
}


void tabDoc::linePaintEvent(QPaintEvent *event)
{
    QPainter painter(lineNumberArea);
    painter.fillRect(event->rect(), Qt::lightGray);

    QTextBlock block = firstVisibleBlock();
    int blockNumber = block.blockNumber();
    int top = qRound(blockBoundingGeometry(block).translated(contentOffset()).top());
    int bottom = top + qRound(blockBoundingRect(block).height());

    while (block.isValid() && top <= event->rect().bottom())
    {
        if (block.isVisible() && bottom >= event->rect().top())
        {
            QString number = QString::number(blockNumber + 1);
            painter.setPen(Qt::black);
            painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), Qt::AlignRight, number);
                }

                block = block.next();
                top = bottom;
                bottom = top + qRound(blockBoundingRect(block).height());
                ++blockNumber;
            }
        }
