#include "remarkupparserthread.h"
#include "JuffScintilla.h"
#include <QMutexLocker>
#include <QDebug>

//TASK queue texts of different docs for parsing. disconnect OnActivated event
void
RemarkupParserThread::run(){
    exec();
}

void
RemarkupParserThread::parseText(){
    qDebug() << "RemarkupParserThread::run";

    if (! parser->isConnected()){
        if (!parser->connect()){
            qDebug()<<"Can't connect.. sleep";
            emit timerRestart();
            return;
        }
    }

    Juff::JuffScintilla* doc = getDoc();
    if (doc == nullptr) return;

    QString text = doc->text();
    if (text.isEmpty()) return;

    Blocks output = parser->parse(text);

//    for (int i=0; i<output.size(); ++i){
//        const Block& block = output.at(i);
//        qDebug() << QString("%1: [%2 - %3]").arg(QString::fromStdString(block.rule)).arg(block.start).arg(block.start+block.num_lines -1);
//    }

    qDebug() << "RemarkupParserThread::text parsed. Sleeping..";
    Juff::JuffScintilla* recheckDoc = getDoc();

    //if doc is changed discard parsed tree
    if (recheckDoc !=doc) return;

    emit updateDoc(output, doc);
}

RemarkupParserThread::RemarkupParserThread(QObject *parent)
    : QThread(parent)
{
    qRegisterMetaType <Blocks> ( "Blocks");

    timerLagging.setInterval(800);
    timerLagging.setSingleShot(true);
    connect(&timerLagging, SIGNAL(timeout()), this, SLOT(parseText()));
    connect(this, SIGNAL(timerRestart()), &timerLagging, SLOT(start()));
    connect(this, SIGNAL(timerStop()), &timerLagging, SLOT(stop()));

    parser = new RemarkupParser();
}

RemarkupParserThread::~RemarkupParserThread(){
    delete parser;
}

Juff::JuffScintilla*
RemarkupParserThread::getDoc(){
    QMutexLocker lock(&docLock);

    return this->doc;
}

void
RemarkupParserThread::processDoc(Juff::JuffScintilla* doc){
    QMutexLocker lock(&docLock);
    this->doc  = doc;

    emit timerRestart();
}

void RemarkupParserThread::stop(){
    QMutexLocker lock(&docLock);
    this->doc  = nullptr;

    emit timerStop();
}

