#include "rebuild_manager.h"

RebuildManager::RebuildManager()
	:ZCWorkThread("MediaReadThread"),
	m_pMqtt(nullptr),
	m_nMqttSuccess(0)
{}
RebuildManager::~RebuildManager()
{
	delete m_pMqtt;
	m_pMqtt = nullptr;
}

bool RebuildManager::Init()
{
	if (!m_configData.LoadConfigFile())
	{
		return false;
	}
	m_pMqtt = new CmdTransportMqtt(m_configData.UuId(), m_configData.RoomId(), this);
	if (!m_pMqtt)
	{
		return false;
	}

	return true;
}

bool RebuildManager::ConnectMqttServer()
{
	if (!m_pMqtt) return false;
	if (!m_pMqtt->ConnectServer(m_configData.MqttUrl())) return false;

	return true;
}
void RebuildManager::DisConnectMqttServer()
{
	if (m_pMqtt)
	{
		m_pMqtt->DisConnectServer();
	}
}

bool RebuildManager::OpenMediaFile()
{
	int nRet = m_fileReader.OpenFile(m_configData.FilePath(), m_configData.MediaKey());
	if (nRet != 0) return false;

	return true;
}
void RebuildManager::CloseMediaFile()
{
	m_fileReader.CloseFile();
}

bool RebuildManager::StartPull()
{
	StartThread();
	return true;
}
void RebuildManager::StopPull()
{
	StopThread();
}
bool RebuildManager::EndOfFile()
{
	return m_fileReader.GetEof();
}
void RebuildManager::DoRunning()
{
	if (!m_fileReader.GetEof())
	{
		AVPacket pkt = { 0 };
		av_init_packet(&pkt);

		int nRet = m_fileReader.ReadFile(pkt);
		if (nRet == -1)
		{
			printf("end of media file ...\n");
			m_fileReader.SetEof(true);
		}
		else
		{
			if (pkt.stream_index == m_fileReader.VideoStreamIndex())
			{
				ParseNaluBySize(pkt);
			}
			else
			{
				av_packet_unref(&pkt);
			}
		}
	}
	else
	{
		std::chrono::milliseconds dura(5);
		std::this_thread::sleep_for(dura);
	}
}

void RebuildManager::OnConnectServerSuccess(bool success)
{
	m_nMqttSuccess = success ? 1 : 2;

	if (success)
	{
		printf("mqtt : connect mqtt server sucess ...\n");
	}
	else
	{
		printf("mqtt : connect mqtt server failed ...\n");
	}
}
void RebuildManager::OnSubscribeTopicSuccess(bool success)
{
	if (success)
	{
		printf("mqtt : subscrible topic sucess ...\n");
	}
	else
	{
		printf("mqtt : subscrible topic failed ...\n");
	}
}
void RebuildManager::OnReceiveMessage(std::string message)
{
	printf("mqtt : receive mqtt message:\n");
	printf("%s\n", message.c_str());
}
void RebuildManager::CallBackWhiteBoardData(AVPacket &pkt)
{
	CFrameInfo info;

	if (GetWhiteBoardData(pkt, info))
	{
		if (info.m_pData[0] == 0 && info.m_pData[1] == 0)
		{
			std::string req((char *)info.m_pData + 6, info.m_nDataSize - 6);

			int index = *(int *)(info.m_pData + 6 + 8);
			printf("whitebaord's data index = %d\n", index);

			if (m_pMqtt)
			{
				m_pMqtt->SendRequest(req);
			}

			info.UnInitFrame();
		}
	}

	av_packet_unref(&pkt);
}