#include "VolumeControl.h"
#include <iostream>
#include <future>

#include "CustomAudioVolumeJson.h"

namespace UkuiAudioFramwork
{
VolumeControl& VolumeControl::getInstance()
{
    static VolumeControl instance;
    return instance;
}

void VolumeControl::init()
{
    // 1. get backend

    // 2. created backend factory
    switch (m_type) {
    case BackendType::PIPEWIRE: {
        m_pBackendFactory = std::make_shared<PipewireBackendFactory>();
        m_pManagerFactory = std::make_shared<PipewireManagerFactory>();
        break;
    }
    case BackendType::PULSEAUDIO: {
        m_pBackendFactory = std::make_shared<PulseaudioBackendFactory>();
        m_pManagerFactory = std::make_shared<PulseaudioManagerFactory>();
        break;
    }
    case BackendType::ALSA:
    case BackendType::JACK:
    default:
        AUDIO_ERROR("Can not support {} backend, exit.", getBackendName(m_type));
        return;
    }

    // 3. created backend
    m_pBackend = m_pBackendFactory->createBackend();
    m_pAudioManager = m_pManagerFactory->createManager();
    m_pAudioManager->init();
    m_pAudioManager->connect();

    AudioMethod::getInstance().setManager(m_pAudioManager);
    AudioMethod::getInstance().init();

    std::thread([this]() {
        auto moduleList = m_pAudioManager->getModuleList();
        AUDIO_DEBUG("The size of the loaded module is {}.", moduleList.size());
        for (const auto& [k, v] : m_settingsMap) {
            bool status = m_statusFunctions[v[0]]();

            if (!status)
                continue;

            auto it = std::find_if(moduleList.begin(), moduleList.end(), [v](const std::string& name) {
                return name == v[1];
            });
            if (it == moduleList.end()) {
                AudioMethod::getInstance().loadModule(v[1], v[2]);
            }
            else {
                AUDIO_DEBUG("Module {} is loaded.", v[1]);
            }
        }
    }).detach();

    AudioMethod::getInstance().run();
}
}
