#include "externalplayerdetector.h"
#include <config/config_keys.h>
#include <config/configstore.h>
#include <QDir>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QStandardPaths>

QList<DetectedPlayer> ExternalPlayerDetector::detect() {
    QList<DetectedPlayer> result;

    auto tryDetect = [&](const QString &name, const QStringList &exeNames,
                         const QStringList &extraDirs = {}) {
        for (const auto &exe : exeNames) {
            QString found = QStandardPaths::findExecutable(exe, extraDirs);
            if (!found.isEmpty()) {
                result.append({name, QDir::toNativeSeparators(found)});
                return;
            }
        }
    };

#if defined(Q_OS_MAC)
    tryDetect("MPV", {"mpv"});
    tryDetect("VLC", {"vlc"}, {"/Applications/VLC.app/Contents/MacOS"});
    tryDetect("IINA", {"iina"}, {"/Applications/IINA.app/Contents/MacOS"});
#else
    tryDetect("MPV", {"mpv"});
    tryDetect("VLC", {"vlc"});
    tryDetect("MPC-Qt", {"mpc-qt"});
#endif
    return result;
}

void ExternalPlayerDetector::saveToConfig(const QList<DetectedPlayer> &players) {
    QJsonArray arr;
    for (const auto &p : players) {
        QJsonObject obj;
        obj["name"] = p.name;
        obj["path"] = p.path;
        arr.append(obj);
    }
    ConfigStore::instance()->set(
        ConfigKeys::ExtPlayerDetectedList,
        QString::fromUtf8(QJsonDocument(arr).toJson(QJsonDocument::Compact)));
}

QList<DetectedPlayer> ExternalPlayerDetector::loadFromConfig() {
    QList<DetectedPlayer> result;
    QString jsonStr = ConfigStore::instance()->get<QString>(ConfigKeys::ExtPlayerDetectedList);
    QJsonArray arr = QJsonDocument::fromJson(jsonStr.toUtf8()).array();
    for (const auto &val : arr) {
        QJsonObject obj = val.toObject();
        QString name = obj["name"].toString();
        QString path = obj["path"].toString();
        if (!name.isEmpty() && !path.isEmpty()) {
            result.append({name, path});
        }
    }
    return result;
}
