#include "roomprofile.h"
#include <QtWidgets/QApplication>
#include <QtCore/QSettings>
#include <QtCore/QUuid>
#include <QtCore/QFile>
#include <QtCore/QString>

#ifdef USE_3TEE_SDK_API_C
	#include "api_c/avdengine_c.h"
	#include "api_c/videorender_c.h"
	static char msgBuf[1024];
	#define SET_OPTION avd_engine_setOption
	#define SET_PARAM avd_engine_setLogParams
#else
	#include "api/avdengine.h"
	#include "api/videorender.h"
	#define SET_OPTION IAVDEngine::Instance()->setOption
	#define SET_PARAM IAVDEngine::Instance()->setLogParams
#endif

#include "appkey.h"

///
QString CRoomProfile::getAppKey() {
	return m_accessKey.isEmpty() ? QString::fromUtf8(tee3_app_key) : m_accessKey;
}
QString CRoomProfile::getSecretKey() {
	return m_secretKey.isEmpty() ? QString::fromUtf8(tee3_secret_key) : m_secretKey;
}

QString CRoomProfile::getErrorInfo(QString amsg, Result ret) {
	QString msg = amsg;
	msg += (QSTRING(" �����룺") + QString::number(ret));
#ifdef USE_3TEE_SDK_API_C
	uint32 msglen = 1024;
	memset(msgBuf, 0, msglen);
	avd_engine_getErrorMessage(ret, msgBuf, msglen);
	msg += (QSTRING(" ������Ϣ��") + QString::fromUtf8(msgBuf));
#else
	msg += (QSTRING(" ������Ϣ��") + QString::fromUtf8(IAVDEngine::Instance()->getErrorMessage(ret).c_str()));
#endif
	
	return msg;
}

CRoomProfile* g_instance = NULL;
CRoomProfile* CRoomProfile::Instance() {
	if (NULL == g_instance) {
		g_instance = new CRoomProfile();
		g_instance->loadProfileFile();
	}
	return g_instance;
}
CRoomProfile::CRoomProfile() {
	m_video_pubtype = vp_single;
	m_datatcp = false;
	m_auto_audio = false;
	m_auto_video = false;
	m_has_livecast = false;
#ifdef USE_3TEE_SDK_API_C
	m_render_scaling_type = Scale_Aspect_Fit;
#else
    m_render_scaling_type = rtc::IVideoRenderView::Scale_Aspect_Fit;
#endif
	m_ismainbroadcaster = true;
	m_lvvideolayout = vl_auto_overlay;
	m_usedGDIRender = false;
	m_audioDelayOffset = 0;
	m_pubMixerVideo = false;
	m_audio_aec_DAEcho = false;
	m_audio_noiseSuppression = true;
	m_audio_autoGainControl = true;
	m_audio_highpassFilter = true;
}
CRoomProfile::~CRoomProfile() {
}

bool CRoomProfile::loadProfileFile() {
	

	// log setting
	QString ini_path = QString("%1/setting.ini").arg(QCoreApplication::applicationDirPath());
	QSettings setting(ini_path, QSettings::IniFormat);
	m_accessKey = setting.value("setting/accessKey").toString().toUtf8().constData();
	m_secretKey = setting.value("setting/secretKey").toString().toUtf8().constData();

	QString loglevel = setting.value("setting/loglevel").toString().toUtf8().constData();
	QString logfile  = setting.value("setting/logfile").toString().toUtf8().constData();
	if (logfile.isEmpty()) {
		QString currentDir = QApplication::applicationDirPath();
		int pos = currentDir.lastIndexOf(QString("\\"));
		if (pos != currentDir.length() - 1) {
			currentDir.append(QString("\\"));
		}
		currentDir.append(QSTRING("Nice2Meet_Log_") + QString::number(QApplication::applicationPid(), 10));
		logfile = currentDir.toUtf8().data();
	}

    //SET_PARAM(loglevel.toUtf8().data(), logfile.toUtf8().data());
	
	// room setting
	m_siteurl	= setting.value("setting/init_site").toString();
	if (m_siteurl.isEmpty()) {
		m_siteurl = tee3_avd_server;
	}
	m_rooturl   = setting.value("setting/rooturl").toString();
	m_inviteurl = setting.value("setting/url").toString();
	m_dtlsflag	= setting.value("setting/mediausedtls").toInt();
	m_roommode	= setting.value("setting/default_mode").toString();
	m_roomid	= setting.value("setting/roomid").toString();
	m_userid	= setting.value("setting/userid").toString();
	m_outgoingAddress = setting.value("setting/outgoingAddress").toString();
	m_outgoingUser = setting.value("setting/outgoingUser").toString();
	m_outgoingPass = setting.value("setting/outgoingPass").toString();
	if (m_userid.isEmpty()) {
		m_userid = QUuid::createUuid().toString();
		m_userid.remove('{');
		m_userid.remove('}');
	}

	// room video setting

	CAMERA_CAP cap;
	cap.width = setting.value("setting/videoWidth").toInt();
	cap.height = setting.value("setting/videoHeight").toInt();
	cap.maxFPS = setting.value("setting/videoFrameRate").toInt();
	if (cap.isValid()) {
		SET_OPTION(eo_camera_capability_default, &cap);
	}
	else {
		//CameraCapability cap(960,720,30);
		//CameraCapability cap(1280, 720, 30);
		//CameraCapability cap(1920, 1080, 30);
		CAMERA_CAP cap(640, 480, 20);
		
		SET_OPTION(eo_camera_capability_default, &cap);
	}
	SET_OPTION(eo_camera_capability_default, &m_maxcap);
	VideoQuality quality;
	quality = (VideoQuality)setting.value("setting/subscribeQuality").toInt();
	if (quality > 0) {
		SET_OPTION(eo_video_quality_subscribe_default, &quality);
	}

	quality = (VideoQuality)setting.value("setting/publishedQuality").toInt();
	if (quality > 0) {
		SET_OPTION(eo_video_quality_publish_default, &quality);
	}

	m_video_ratio = (VideoRatio)setting.value("setting/videoRation").toInt();
	SET_OPTION(eo_video_ration_default, &m_video_ratio);
	m_video_codec = (VideoCodec)setting.value("setting/videoCodec").toInt();
	SET_OPTION(eo_video_codec_priority, &m_video_codec);
	m_audio_codec = String(setting.value("setting/audioCodec").toString().toUtf8());

	m_video_pubtype = (VideoPubType)setting.value("setting/publishOption").toInt();
	if (vp_3_svc == m_video_pubtype) {
		bool svc = true;
		SET_OPTION(eo_video_publish_svc_default, &svc);
	}

	
	m_render_scaling_type = SCALING_TYPE(setting.value("setting/renderScalingType").toInt());
	
	m_rtmpurl = setting.value("setting/rtmp_site").toString();
	m_hlsurl = setting.value("setting/hls_site").toString();

	QString vrender = setting.value("setting/videorender").toString();
	if (vrender.toLower() == QString("gdi")) {
		m_usedGDIRender = true;
	}

	m_audioDelayOffset = SCALING_TYPE(setting.value("setting/audioDelayOffset").toInt());
	
	m_audio_aec_DAEcho = setting.value("setting/audioAecDAEcho").toInt();
	m_audio_noiseSuppression = setting.value("setting/audioNoiseSuppression").toInt();
	m_audio_autoGainControl = setting.value("setting/audioAutoGainControl").toInt();
	m_audio_highpassFilter = setting.value("setting/audioHighpassFilter").toInt();

	QString iptag = setting.value("setting/mcuParamsipTag").toString();
	QString idccode = setting.value("setting/mcuParamsidcCode").toString();
	m_route_params = "{\"ip_tag\":\"" + iptag + "\",\"idc_code\":\"" + idccode + "\"}";
	return true;
}

const QString& CRoomProfile::GetInviteUrl() {
	if (m_inviteurl.isEmpty()) {
		m_inviteurl = m_rooturl + QSTRING("jroom");
	}
	return m_inviteurl;
}
void CRoomProfile::writeSetting(const QString &key, const QVariant &value) {
	QString ini_path = QString("%1/setting.ini").arg(QCoreApplication::applicationDirPath());
	QSettings setting(ini_path, QSettings::IniFormat);
	setting.setValue(key, value);
}

void CRoomProfile::SetRoomID(const QString& value) {
	if (value == m_roomid) {
		return;
	}
	writeSetting("setting/roomid", value);
	m_roomid = value;
}
void CRoomProfile::SetUserID(const QString& value) {
	if (value == m_userid) {
		return;
	}
	m_userid = value;
}
void CRoomProfile::SetOutgoingAddress(const QString& value) {
	if (value == m_outgoingAddress) {
		return;
	}
	writeSetting("setting/outgoingAddress", value);
	m_outgoingAddress = value;
}
void CRoomProfile::SetOutgoingUser(const QString& value) {
	if (value == m_outgoingUser) {
		return;
	}
	writeSetting("setting/outgoingUser", value);
	m_outgoingUser = value;
}
void CRoomProfile::SetOutgoingPass(const QString& value) {
	if (value == m_outgoingPass) {
		return;
	}
	writeSetting("setting/outgoingPass", value);
	m_outgoingPass = value;
}
bool CRoomProfile::SetVideoRatio(VideoRatio value) {
	if (value == m_video_ratio) {
		return false;
	}
	m_video_ratio = value;
	SET_OPTION(eo_video_ration_default, &m_video_ratio);
	writeSetting("setting/videoRation", m_video_ratio);
	return true;
}
bool CRoomProfile::SetVideoCodec(VideoCodec value) {
	if (value == m_video_codec) {
		return false;
	}
	m_video_codec = value;
	SET_OPTION(eo_video_codec_priority, &m_video_codec);
	writeSetting("setting/videoCodec", m_video_codec);
	return true;
}
bool CRoomProfile::SetVideoPubType(VideoPubType value) {
	if (value == m_video_pubtype) {
		return false;
	}
	m_video_pubtype = value;
	bool issvc = (vp_3_svc == m_video_pubtype);
	SET_OPTION(eo_video_publish_svc_default, &issvc);
	writeSetting("setting/publishOption", m_video_pubtype);
	return true;
}
bool CRoomProfile::SetDtls(bool value) {
	if (value == m_dtlsflag) {
		return false;
	}
	m_dtlsflag = value;
	writeSetting("setting/mediausedtls", (m_dtlsflag ? 1 : 0));
	return true;
}
bool CRoomProfile::SetDataTcp(bool value) {
	if (value == m_datatcp) {
		return false;
	}
	m_datatcp = value;
	SET_OPTION(eo_data_channel_tcp_priority, &m_datatcp);
	return true;
}
bool CRoomProfile::SetAutoVideo(bool value) {
	if (value == m_auto_video) {
		return false;
	}
	m_auto_video = value;
	return true;
}
bool CRoomProfile::SetAutoAudio(bool value) {
	if (value == m_auto_audio) {
		return false;
	}
	m_auto_audio = value;
	return true;
}
bool CRoomProfile::SetLivecast(bool value) {
	if (value == m_has_livecast) {
		return false;
	}
	m_has_livecast = value;
	return true;
}

void CRoomProfile::SetMainBroadcaster(bool value) {
	m_ismainbroadcaster = value;
}
void CRoomProfile::SetLivecastVideoLayout(MixerVideoLayoutType value) {
	m_lvvideolayout = value;
}
void CRoomProfile::SetPubMixerVideo(bool value) {
	m_pubMixerVideo = value;
}
bool CRoomProfile::SetRenderType(SCALING_TYPE renderType) {
	if (renderType == m_render_scaling_type) {
		return false;
	}
	m_render_scaling_type = renderType;
	writeSetting("setting/renderScalingType", m_video_codec);
	return true;
}
///
QString CRoomProfile::GetLogo() const {
	QString logoImage("./logo.png");
	QFile mFile(logoImage);
	if (!mFile.exists()) {
		logoImage = QString(":/nice2meet/Resources/image/logo.png");
	}
	return logoImage;
}
QImage CRoomProfile::GetTitleBarLogo() const {
	QImage logoImage("./logoinside.png");
	if (logoImage.isNull()) {
		logoImage = QImage(":/nice2meet/Resources/image/logoinside.png");
	}
	return logoImage;
}
QIcon CRoomProfile::GetAppIcon() const {
	QFile mFile("./app_icon.ico");
	if (mFile.exists()) {
		return QIcon("./app_icon.ico");
	}
	else {
		return QIcon(":/nice2meet/Resources/image/app_icon.ico");
	}
}

