#include "parsechecks.h"
#include "StoryBoardDocumentParser.h"
#include "StoryUnitDocumentParser.h"
#include "../WordsIDE/opstream.h"

using namespace Parse;

CheckTools::FragmentsCheck::FragmentsCheck(Parse::Result::ParseCore *const core)
    : core_ins(core){}

bool CheckTools::FragmentsCheck::check(QList<Parse::ErrorMessage> &reasons) const
{
    auto stories = core_ins->allStoryBoards();

    // 编排索引顺序校验
    for(auto &ins : stories){
        auto xins = static_cast<Parse::NodeStoryBoard*>(ins);

        double temp = -DBL_MAX;
        auto refers = xins->children();
        for(auto &ref : refers){
            if(ref->typeValue() == NODE_FRAGMENTREFERENCE){
                auto ins_ref = static_cast<NodeStoryFragmentRefer*>(ref);
                auto u = core_ins->queryStoryUnit(ins_ref->unit());
                if(!u.size())
                    continue;

                auto frag = core_ins->queryStoryFragment(u[0], ins_ref->fragment());
                if(!frag.size())
                    continue;

                auto frag_ins = static_cast<NodeStoryFragment*>(frag[0]);

                bool isvalid;
                double order_value = frag_ins->orderValue(isvalid);
                if(temp > order_value)
                {
                    ErrorMessage msg(ins_ref);
                    msg.CodeRow = ins_ref->refered().first()->row();
                    msg.CodeCol = ins_ref->refered().first()->column();
                    msg.FilePath = ins_ref->doc()->filePath();
                    msg.Text = ins_ref->unit() + "："+ ins_ref->fragment();
                    msg.Reason = QString("%1：指定节点索引顺序颠倒").arg(ins_ref->fragment());

                    reasons << msg;
                    return false;
                }

                temp = order_value;
            }
        }
    }

    return true;
}
