class Helper : public QObject {
    Q_OBJECT

public:
    Helper(MSAFlows * context) : QObject(), context_(context), msg_(QString()) {
        QFile tokenCache("usercache.dat");
        if(tokenCache.open(QIODevice::ReadOnly)) {
            context_->resumeFromState(tokenCache.readAll());
        }
    }

public slots:
    void run() {
        connect(context_, &MSAFlows::activityChanged, this, &Helper::onActivityChanged);
        context_->silentSignIn();
    }

    void onFailed() {
        qDebug() << "Login failed";
    }

    void onActivityChanged(Katabasis::Activity activity) {
        if(activity == Katabasis::Activity::Idle) {
            switch(context_->validity()) {
                case Katabasis::Validity::None: {
                    // account is gone, remove it.
                    QFile::remove("usercache.dat");
                }
                break;
                case Katabasis::Validity::Assumed: {
                    // this is basically a soft-failed refresh. do nothing.
                }
                break;
                case Katabasis::Validity::Certain: {
                    // stuff got refreshed / signed in. Save.
                    auto data = context_->saveState();
                    QSaveFile tokenCache("usercache.dat");
                    if(tokenCache.open(QIODevice::WriteOnly)) {
                        tokenCache.write(context_->saveState());
                        tokenCache.commit();
                    }
                }
                break;
            }
        }
    }

private:
    MSAFlows *context_;
    QString msg_;
};
