#pragma once

#include <string>
#include "json/json.h"

const std::string kMqttUrl  = "mqtt_url";
const std::string kRoomId	= "roomid";
const std::string kUuId		= "uuid";
const std::string kFilePath = "filepath";
const std::string kMediaKey	= "key";

class GlobalData
{
public:
	GlobalData()
		:m_sRoomId(""),
		m_sUuId(""),
		m_sFilePath(""),
		m_sMediaKey("")
	{
	}
	~GlobalData(){}

	bool LoadConfigFile()
	{
		FILE *file = fopen("./wb_rebuild_config.ini", "r");
		if (file == NULL)
		{
			printf("error : open config file failed\n");
			return false;
		}

		long fileSize = 0;
		fseek(file, 0, SEEK_END);
		fileSize = ftell(file);
		if (fileSize <= 0)
		{
			printf("error : config file size is zero\n");
			return false;
		}

		char *p = new char[fileSize];
		rewind(file);

		long ret = fread(p, 1, fileSize, file);
		if (ret <= 0)
		{
			printf("error : read config file error\n");

			delete p;
			fclose(file);
			return false;
		}

		std::string message(p);
		delete p;

		Json::Value root;
		Json::CharReaderBuilder readerBuilder;

		std::unique_ptr<Json::CharReader> const reader(readerBuilder.newCharReader());

		const char *start_pos = message.c_str();

		std::string err;
		if (!reader->parse(start_pos, start_pos + message.length(), &root, &err))
		{
			printf("error : config file is not json format\n");
			return false;
		}

		m_sMediaKey = "";

		if (!root[kRoomId] || !root[kUuId] || !root[kFilePath])
		{
			printf("error : no roomid uuid filepath param\n");
			return false;
		}

		m_sMqttUrl  = root[kMqttUrl].asString();
		m_sRoomId	= root[kRoomId].asString();
		m_sUuId		= root[kUuId].asString();
		m_sFilePath = root[kFilePath].asString();
		
		if (root[kMediaKey])
		{
			m_sMediaKey = root[kMediaKey].asString();
		}
		
		return true;
	}

	std::string MqttUrl() { return m_sMqttUrl; }
	std::string RoomId() { return m_sRoomId; }
	std::string UuId() { return m_sUuId; }
	std::string FilePath() { return m_sFilePath; }
	std::string MediaKey() { return m_sMediaKey; }

private:
	std::string m_sMqttUrl;
	std::string m_sRoomId;
	std::string m_sUuId;
	std::string m_sFilePath;
	std::string m_sMediaKey;
};