// Copyrigth Xtooltech @ 2023- All rights reserved.(LXH)

#include "StationDataReportRecord.hpp"
#include "cJSON.h"

namespace otx {
	namespace jidu {
		StationDataReportRecord::StationDataReportRecord() {
			this->mOverallResult = "OK";
		}
		StationDataReportRecord::~StationDataReportRecord() {
			// mTestData中的数据仅仅是引用，它们由category对象管理。
			int size = this->mTestCategories.size();
			for (int i = 0; i < size; i++) {
				StationDataCategory* item = this->mTestCategories[i];
				delete item;
			}
			this->mTestCategories.clear();
			this->mTestData.clear();// 仅仅clear一次。
		}

		std::string StationDataReportRecord::getOverallResult() {
			return this->mOverallResult;
		}
		void StationDataReportRecord::setOverallResult(const std::string& v) {
			this->mOverallResult = v;
		}

		std::vector<StationDataBlock*>* StationDataReportRecord::getTestData() {
			return &this->mTestData;
		}
		void StationDataReportRecord::addStationDataBlock(StationDataBlock* block) {
			this->mTestData.push_back(block);
		}

		std::vector<StationDataCategory*>* StationDataReportRecord::getTestCategories() { return &this->mTestCategories; }
		StationDataCategory* StationDataReportRecord::getTestCategoryById(const std::string& v) {
			int size = this->mTestCategories.size();
			StationDataCategory* result = nullptr;
			for (int i = 0; i < size; i++) {
				StationDataCategory* item = this->mTestCategories[i];
				if (item->getTestStatisticId() == v) {
					result = item;
					break;
				}
			}
			return result;
		}
		StationDataCategory* StationDataReportRecord::newCategory() {
			StationDataCategory* result = new StationDataCategory();
			this->mTestCategories.push_back(result);
			return result;
		}

		std::string StationDataReportRecord::toJsonString() {
			std::string result;

			cJSON* obj = cJSON_Parse(ReportRecord::toJsonString().c_str());

			if (this->mOverallResult.size() > 0) {
				cJSON_AddStringToObject(obj, "overallResult", this->mOverallResult.c_str());
			}

			int size = this->mTestData.size();
			if (size > 0) {
				cJSON* arrObj = cJSON_CreateArray();
				for (int i = 0; i < size; i++) {

					cJSON* tempItem = cJSON_Parse(this->mTestData[i]->toJsonString().c_str());
					cJSON_AddItemToArray(arrObj, tempItem);
				}
				cJSON_AddItemToObject(obj, "testData", arrObj);
			}

			char* tepm = cJSON_PrintUnformatted(obj);
			cJSON_Delete(obj);
			result = tepm;
			cJSON_free(tepm);
			return result;
		}

	} // namespace jidu
} // namespace otx
