#include "com_room.h"
#include <QTimer>
#include "log2ui.h"
#include "dlg_userInfo.h"
#include "use_audio.h"
#include "use_video.h"

QString g_roomid = "12345678917";
using namespace rtc;

///
Com_Room::Com_Room(QWidget *parent) : QWidget(parent) {
	ui.setupUi(this);
    //ui.edt_roomId->setText(Utf8Str("r8216"));
    ui.edt_roomId->setText(g_roomid);
	connect(ui.btn_roomJoin, SIGNAL(toggled(bool)), this, SLOT(on_join_leaveRoom(bool)));
	connect(ui.ckb_room_stats, SIGNAL(toggled(bool)), this, SLOT(on_enableStats(bool)));
	resetControls(false);
	ButtonChecked(ui.btn_roomJoin, false, Utf8Str("加入房间"));
	timer_ = NULL;
}
Com_Room::~Com_Room() {
}

bool Com_Room::isWorking() const {
	return !roomIsInit() ? false : api_isWorking();
}
///
#define qDebug_Room qDebug() << Utf8Str("--- Room ") << roomId_.c_str() 
bool Com_Room::on_join_leaveRoom(bool isJoin) {
	bool ret = false;
	if (isJoin) {
		ret = joinRoom();
	}
	else {
		ret = leaveRoom();
	}
	if (ret) {
		ButtonChecked(ui.btn_roomJoin, isJoin, (isJoin ? Utf8Str("离开房间") : Utf8Str("加入房间")));
	}
	return ret;
}
bool Com_Room::joinRoom() {
	if (isWorking()) { return false; }

	Dlg_UserInfo dlg(NULL);
	int rec = dlg.exec();
	if (rec == QDialog::Rejected) {
		return false;
	}
	if (dlg.getUserName().isEmpty()) {
		dlg.showUserNameEmpty();
		return false;
	}

	std::string roomId = ui.edt_roomId->text().toUtf8().data();
	if (roomId.empty()) {

		return false;
	}
	
	Result ret = api_joinRoom(
		roomId.c_str(),
		GetRandomNumberWithPrefix("htd").c_str(),	//标示房间中唯一用户，必须填写
		dlg.getUserName().toUtf8().data(),			//非必须
		dlg.getUserData().toUtf8().data());			//非必须
	if (RT_SUCCEEDED(ret)) {
		roomId_ = roomId; 
	}
	qDebug_Room << Utf8Str(" 开始加入 ") << OutputWithRet(ret);
	return RT_SUCCEEDED(ret);
}
bool Com_Room::leaveRoom() {
	if (!roomIsInit()){
		return false;
	}
    if (ui.audio) {
        ui.audio->onDetach();
	}
    if (ui.video) {
        ui.video->onDetach();
	}
    if(ui.screen){
        ui.screen->onDetach();
    }
	api_leaveRoom();
	resetControls(false);
	qDebug_Room << Utf8Str(" 离开 ") << OutputWithRet(AVD_OK);
	return true;
}

bool Com_Room::on_sendPublicData() {
	if (isWorking()) { return false; }

	return false;
}
bool Com_Room::on_sendPrivateData() {
	if (isWorking()) { return false; }

	return false;
}
bool Com_Room::on_updateAppData() {
	if (isWorking()) { return false; }

	return false;
}
bool Com_Room::on_enableStats(bool enable) {
	if (enable) {
		if (NULL == timer_) {
			timer_ = new QTimer(this);
			timer_->setInterval(3000);
			connect(timer_, SIGNAL(timeout()), this, SLOT(on_timerOut()));
		}
		timer_->start();
	}
	else {
		timer_->stop();
	}
	return (roomIsInit() && RT_SUCCEEDED(api_enableStats(enable)));
}
void Com_Room::on_timerOut() {
	if (!isWorking()) { return; }
	rtc::NetworkStats netstats = getRoomNetStats();
	QString stemp;
	stemp.sprintf("%d", netstats.bps_sent / 1024);
	ui.gpb_stats_send->setText(stemp);
	ui.gpb_stats_send->update();
	stemp.sprintf("%d", netstats.bps_received / 1024);
	ui.gpb_stats_recv->setText(stemp);
	ui.gpb_stats_recv->update();
}
void Com_Room::resetControls(bool enable) {
	ui.ckb_room_stats->setEnabled(enable);
	ui.gpb_stats_send->setText(Utf8Str("0"));
	ui.gpb_stats_recv->setText(Utf8Str("0"));
}

///
void Com_Room::onJoinResult(Result result) {
	qDebug_Room << Utf8Str(" 加入：") << OutputWithRet(result);
	if (RT_SUCCEEDED(result)) {
		resetControls(true);
		modulesAttach();
	}
}
void Com_Room::onLeaveIndication(Result reason, const UserId& fromId) {
	qDebug_Room << Utf8Str(" 被踢出：") << OutputWithRet(reason);
}
void Com_Room::onPublicData(const char* data, uint32 len, const UserId& fromId) {
	qDebug_Room << Utf8Str(" 接收到私人通道数据：") << len << Utf8Str(" 用户：") << fromId.c_str();
}
void Com_Room::onPrivateData(const char* data, uint32 len, const UserId& fromId) {
	qDebug_Room << Utf8Str(" 接收到公共通道数据：") << len << Utf8Str(" 用户：") << fromId.c_str();
}
void Com_Room::onAppDataNotify(const String& key, const String& value) {
	qDebug_Room << Utf8Str(" 接收应用数据更新：key=") << key.c_str() << Utf8Str("  value=") << value.c_str();
}
void Com_Room::onRoomStatusNotify(RoomStatus status){
	// SDK暂时无效
}
void Com_Room::onConnectionStatus(ConnectionStatus status) {
	qDebug_Room << Utf8Str(" 网络状态：") << status;
}
void Com_Room::onOutgoingInviteStatusNotify(rtc::OutgoingInviteType type, std::string roomId, std::string addr, rtc::OutgoingStatus status, std::string  msg){
    qDebug_Room << Utf8Str(" onOutgoingInviteStatusNotify") << status;
}
void Com_Room::onStreamKeepAliveTimeoutNotify(std::string userId, std::string userName, int mediaType, std::string deviceId, int ssrc){
    qDebug_Room << Utf8Str(" onStreamKeepAliveTimeoutNotify") << userId.c_str();
}
