#include "tools.h"
#include <QWidget>
#include <QAction>

using namespace Tools;



Run::Run(bool manual_flag, std::function<bool ()> judge, std::function<void (bool)> execution)
    : manual(manual_flag), judgement(judge), execution(execution){}

void Run::exec()
{
    if(!manual)
        execution(judgement());
}

StatusSyncCore::StatusSyncCore(QObject *p)
    : QObject(p){}

void StatusSyncCore::widgetEnableSync(QWidget *tar, std::function<bool()> proc) { widget_trigger_map[tar] = proc; }

void StatusSyncCore::actionEnableSync(QAction *tar, std::function<bool()> proc) { action_trigger_map[tar] = proc; }

void StatusSyncCore::actionCheckSync(QAction *tar, std::function<bool()> proc) {
    tar->setCheckable(true);
    registerTrigger(proc, [tar](bool state) {
        if (tar->isChecked() != state)
            tar->setChecked(state);
    });
}

void StatusSyncCore::registerTrigger(std::function<bool()> judge, std::function<void(bool)> exec) {
    auto run = new Run(false, judge, exec);
    alltriggers << run;
}

Run *StatusSyncCore::registerManualRun(std::function<bool ()> judge, std::function<void (bool)> exec)
{
    auto run = new Run(true, judge, exec);
    alltriggers << run;
    return run;
}

void StatusSyncCore::sync()
{
    for(auto &it : widget_trigger_map.keys()){
        auto status = widget_trigger_map[it]();
        if(it->isEnabled() != status)
            it->setEnabled(status);
    }

    for(auto &it : action_trigger_map.keys()){
        auto status = action_trigger_map[it]();
        if(it->isEnabled() != status)
            it->setEnabled(status);
    }

    for(auto &act : alltriggers){
        act->exec();
    }
}

