#include "use_audio.h"
#include "log2ui.h"
#include "api/avdengine.h"

using namespace rtc;

///
Use_Audio::Use_Audio(QWidget *parent) : Com_Audio(parent), module_(NULL) {
}
Use_Audio::~Use_Audio() {
}
void Use_Audio::onAttach(rtc::IRoom* room) {
	if (nullptr == room) {
		module_ = nullptr;
	}
	else {
		module_ = IMAudio::getAudio(room);
		module_->setListener(this);
	}
	Com_Audio::onAttach();
}
void Use_Audio::onDetach() {
	if (module_) {
		module_->setListener(NULL);
	}
	module_ = NULL;
	Com_Audio::onDetach();
}
void Use_Audio::updateLocalMicrophones() {
	if (!isAttach()) {
		return;
	}
	Com_Audio::updateLocalMicrophones();
	IAudioDevice* devices = module_->getAudioDevice();
	MicrophonesType items;
	devices->getMicrophones(items);
	for (Microphone var : items) {
		QListWidgetAddItem(ui.lst_audio_localMicrophones, var.name.c_str(), var.id.c_str());
	}
}
void Use_Audio::updateLocalSpeakers() {
	if (!isAttach()) {
		return;
	}
	Com_Audio::updateLocalSpeakers();
	IAudioDevice* devices = module_->getAudioDevice();
	SpeakersType items;
	devices->getSpeakers(items);
	for (Speaker var : items) {
		QListWidgetAddItem(ui.lst_audio_localSpeakers, var.name.c_str(), var.id.c_str());
	}
}
///
bool Use_Audio::api_engineSetOption(rtc::EngineOption option, void* value) {
	IAVDEngine::Instance()->setOption(option, value);
	return true;
}
bool Use_Audio::api_roomSetOption(rtc::RoomOption option, std::string& value) {
	module_->getRoom()->setOption(ro_audio_option_codec, &value);
	return true;
}
Result Use_Audio::api_openMicrophone(bool open) {
	return open ? module_->openMicrophone() : module_->closeMicrophone();
}
Result Use_Audio::api_muteMicrophone(bool mute) {
	return mute ? module_->muteMicrophone() : module_->unmuteMicrophone();
}
Result Use_Audio::api_muteSpeaker(bool mute) {
	return mute ? module_->muteSpeaker() : module_->unmuteSpeaker();
}
Result Use_Audio::api_monitorAudioLevel(bool enable) {
	return enable ? module_->monitorAudioLevel() : module_->unmonitorAudioLevel();
}
Result Use_Audio::api_setRecordingMicrophone(const rtc::DeviceId& curId) {
	return module_->getAudioDevice()->setRecordingMicrophone(curId);
}
Result Use_Audio::api_setPlayoutSpeaker(const rtc::DeviceId& curId) {
	return module_->getAudioDevice()->setPlayoutSpeaker(curId);
}
Result Use_Audio::api_applyPlayoutGain(float gain) {
	return IAVDEngine::Instance()->setOption(eo_audio_agc_PlayoutGainMultipleValue, &gain);
}

