#include "tray_visuals.h"

#include <QApplication>
#include <QStyle>

namespace {
QIcon fallbackIcon(QStyle::StandardPixmap pixmap)
{
    return QApplication::style()->standardIcon(pixmap);
}

QIcon resourceIcon(const QString &path, QStyle::StandardPixmap fallback)
{
    const QIcon icon(path);
    return icon.isNull() ? fallbackIcon(fallback) : icon;
}
}

TrayIconState trayIconStateForSnapshot(const QJsonObject &snapshot, bool backendAvailable, bool spinnerPhase)
{
    if (!backendAvailable) {
        return TrayIconState::Issue;
    }

    const QString state = snapshot.value(QStringLiteral("backendState")).toString();
    const QJsonObject prefs = snapshot.value(QStringLiteral("prefs")).toObject();

    if (state == QStringLiteral("Running")) {
        if (prefs.value(QStringLiteral("advertisesExitNode")).toBool()) {
            return TrayIconState::AsExitNode;
        }
        if (!prefs.value(QStringLiteral("exitNodeID")).toString().trimmed().isEmpty()) {
            return TrayIconState::ExitNode;
        }
        return TrayIconState::Connected;
    }
    if (state == QStringLiteral("Starting")) {
        return spinnerPhase ? TrayIconState::ConnectingA : TrayIconState::ConnectingB;
    }
    if (state == QStringLiteral("Stopped")) {
        return TrayIconState::Disconnected;
    }
    return TrayIconState::Logo;
}

QIcon iconForTrayState(TrayIconState state)
{
    switch (state) {
    case TrayIconState::Logo:
        return resourceIcon(QStringLiteral(":/mirage/logo.png"), QStyle::SP_ComputerIcon);
    case TrayIconState::Issue:
        return resourceIcon(QStringLiteral(":/mirage/issue.png"), QStyle::SP_MessageBoxCritical);
    case TrayIconState::Disconnected:
        return resourceIcon(QStringLiteral(":/mirage/disconn.png"), QStyle::SP_ComputerIcon);
    case TrayIconState::Connected:
        return resourceIcon(QStringLiteral(":/mirage/conn.png"), QStyle::SP_DialogApplyButton);
    case TrayIconState::ConnectingA:
        return resourceIcon(QStringLiteral(":/mirage/ing1.png"), QStyle::SP_BrowserReload);
    case TrayIconState::ConnectingB:
        return resourceIcon(QStringLiteral(":/mirage/ing2.png"), QStyle::SP_BrowserReload);
    case TrayIconState::ExitNode:
        return resourceIcon(QStringLiteral(":/mirage/exit.png"), QStyle::SP_DriveNetIcon);
    case TrayIconState::AsExitNode:
        return resourceIcon(QStringLiteral(":/mirage/asexit.png"), QStyle::SP_DialogApplyButton);
    }
    return fallbackIcon(QStyle::SP_ComputerIcon);
}
