#include <QtGui>

#include "codeeditor.h"


void CodeEditor::CurrentDBGLine(int i)
{
    QList<QTextEdit::ExtraSelection> extraSelections;

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

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

        selection.format.setBackground(lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        //selection.cursor = textCursor();
        //selection.cursor = this->setPosition(i);
        selection.cursor = QTextCursor(this->document()->findBlockByLineNumber(i - 1)); // ln-1 because line number starts from 0
        selection.cursor.clearSelection();
        extraSelections.append(selection);

        QTextCursor cursor(this->document()->findBlockByLineNumber(i - 1));
        this->setTextCursor(cursor);

    }

    setExtraSelections(extraSelections);
}


//![constructor]
void CodeEditor::setFileName(QString sfile)
{
    QFile file(sfile);

    sfileName = sfile;

    if (file.open(QFile::ReadOnly | QFile::Text))
    {
        QTextStream in(&file);
        this->setPlainText(in.readAll());
    }
}



void CodeEditor::saveFile()
{
    QFile file(sfileName);

    if (!file.open(QFile::WriteOnly | QFile::Text))
    {
        return;
    }

    QTextStream out(&file);
    out << this->toPlainText();
    if (iMode == 1)
    {
        /* if happening in RAM then copy buffer and send signal */
        memcpy(c_code_data, (this->toPlainText()).toStdString().c_str(), 4095);
        Q_EMIT code_edit_text_changed();
    }
}

CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent)
{
    iMode          = 0;
    lineNumberArea = new LineNumberArea(this);

    highlighter = new Highlighter(this->document());

    QTextDocument *doc = this->document();
    QFont         font = doc->defaultFont();
    int           i    = font.pointSize();
    font.setPointSize(i + 8);
    //font.setFamily("Courier New");
    //font.setBold(true);
    doc->setDefaultFont(font);


    connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
    connect(this, SIGNAL(updateRequest(QRect, int)), this, SLOT(updateLineNumberArea(QRect, int)));
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
    connect(this, SIGNAL(textChanged()), this, SLOT(saveFile()));

    connect(this, SIGNAL(mPropagateHIDClick(int)), this, SLOT(mPropagateHIDClickSlot(int)));
    //connect(this, SIGNAL(mouseDoubleClickEvent(QMouseEvent * e)), this, SLOT(slot_mouseDoubleClickEvent(QMouseEvent * e)));

    updateLineNumberAreaWidth(0);
    highlightCurrentLine();
}

void CodeEditor::mPropagateHIDClickSlot(int i)
{
    qDebug() << "HID click" << __FILE__ << __FUNCTION__;
}


void CodeEditor::slot_mouseDoubleClickEvent(QMouseEvent *e)
{
    qDebug() << "this is mouse click\r\n";
    printf("--->\r\n");
    fflush(stdout);
}

//![constructor]

//![extraAreaWidth]



int CodeEditor::lineNumberAreaWidth()
{
    int digits = 1;
    int max    = qMax(1, blockCount());

    while (max >= 10)
    {
        max /= 10;
        ++digits;
    }

    int space = 3 + 10;//fontMetrics().width(QLatin1Char('9')) * digits;

    return (space);
}

//![extraAreaWidth]

//![slotUpdateExtraAreaWidth]



void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
    setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}

//![slotUpdateExtraAreaWidth]

//![slotUpdateRequest]



void CodeEditor::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);
    }
}

//![slotUpdateRequest]

//![resizeEvent]



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

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

//![resizeEvent]

//![cursorPositionChanged]



void CodeEditor::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);
    }

    QString text = this->textCursor().block().text();
    Q_EMIT current_line_changed(text);

    setExtraSelections(extraSelections);
}

//![cursorPositionChanged]

//![extraAreaPaintEvent_0]



void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
    QPainter painter(lineNumberArea);

    painter.fillRect(event->rect(), Qt::lightGray);

//![extraAreaPaintEvent_0]

//![extraAreaPaintEvent_1]
    QTextBlock block       = firstVisibleBlock();
    int        blockNumber = block.blockNumber();
    int        top         = (int)blockBoundingGeometry(block).translated(contentOffset()).top();
    int        bottom      = top + (int)blockBoundingRect(block).height();
//![extraAreaPaintEvent_1]

//![extraAreaPaintEvent_2]
    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 + (int)blockBoundingRect(block).height();
        ++blockNumber;
    }
}
//![extraAreaPaintEvent_2]

