#include "CustomStep.h"

#include "minecraft/auth/AuthRequest.h"
#include "minecraft/auth/Parsers.h"
#include "minecraft/auth/Yggdrasil.h"

CustomStep::CustomStep(AccountData* data, QString password) : AuthStep(data), m_password(password) {
    m_yggdrasil = new Yggdrasil(m_data, this);

    connect(m_yggdrasil, &Task::failed, this, &CustomStep::onAuthFailed);
    connect(m_yggdrasil, &Task::succeeded, this, &CustomStep::onAuthSucceeded);
    connect(m_yggdrasil, &Task::aborted, this, &CustomStep::onAuthFailed);
}

CustomStep::~CustomStep() noexcept = default;

QString CustomStep::describe() {
    return tr("Logging in with Custom account.");
}

void CustomStep::rehydrate() {
    // NOOP, for now.
}

void CustomStep::perform() {
    qWarning() << "url: " << m_url << " / " << m_data->customUrl;
    if(m_password.size()) {
        m_yggdrasil->login(m_password, m_url + "/auth/");
    }
    else {
        m_yggdrasil->refresh(m_data->customUrl + "/auth/");
    }
}

void CustomStep::setUrl(QString url) {
    this->m_url = url;
}

void CustomStep::onAuthSucceeded() {
    emit finished(AccountTaskState::STATE_WORKING, tr("Logged in with Custom"));
}

void CustomStep::onAuthFailed() {
    // TODO: hook these in again, expand to MSA
    // m_error = m_yggdrasil->m_error;
    // m_aborted = m_yggdrasil->m_aborted;

    auto state = m_yggdrasil->taskState();
    QString errorMessage = tr("Custom user authentication failed.");

    // NOTE: soft error in the first step means 'offline'
    if(state == AccountTaskState::STATE_FAILED_SOFT) {
        state = AccountTaskState::STATE_OFFLINE;
        errorMessage = tr("Custom user authentication ended with a network error. Is MutliFactor Auth correct?");
    }
    emit finished(state, errorMessage);
}
