summaryrefslogtreecommitdiffstats
path: root/src/WorldStorage/StatSerializer.cpp
blob: 5c6724c607fb5f40f813cb516b9462c061617dd7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126

// StatSerializer.cpp


#include "Globals.h"
#include "StatSerializer.h"

#include "../Statistics.h"

#include <fstream>





cStatSerializer::cStatSerializer(const AString& a_WorldName, const AString& a_PlayerName, cStatManager* a_Manager)
	: m_Manager(a_Manager)
{
	AString StatsPath;
	Printf(StatsPath, "%s/stats", a_WorldName.c_str());

	m_Path = StatsPath + "/" + a_PlayerName + ".dat";

	/* Ensure that the directory exists. */
	cFile::CreateFolder(FILE_IO_PREFIX + StatsPath);
}





bool cStatSerializer::Load(void)
{
	AString Data = cFile::ReadWholeFile(FILE_IO_PREFIX + m_Path);
	if (Data.empty())
	{
		return false;
	}

	Json::Value Root;
	Json::Reader Reader;

	if (Reader.parse(Data, Root, false))
	{
		return LoadStatFromJSON(Root);
	}

	return false;
}





bool cStatSerializer::Save(void)
{
	Json::Value Root;
	SaveStatToJSON(Root);

	cFile File;
	if (!File.Open(FILE_IO_PREFIX + m_Path, cFile::fmWrite))
	{
		return false;
	}

	Json::StyledWriter Writer;
	AString JsonData = Writer.write(Root);

	File.Write(JsonData.data(), JsonData.size());
	File.Close();

	return true;
}





void cStatSerializer::SaveStatToJSON(Json::Value & a_Out)
{
	for (unsigned int i = 0; i < (unsigned int)statCount; ++i)
	{
		StatValue Value = m_Manager->GetValue((eStatistic) i);

		if (Value != 0)
		{
			const AString & StatName = cStatInfo::GetName((eStatistic) i);

			a_Out[StatName] = Value;
		}
	}
}





bool cStatSerializer::LoadStatFromJSON(const Json::Value & a_In)
{
	m_Manager->Reset();

	for (Json::ValueIterator it = a_In.begin() ; it != a_In.end() ; ++it)
	{
		AString StatName = it.key().asString();

		eStatistic StatType = cStatInfo::GetType(StatName);

		if (StatType == statInvalid)
		{
			LOGWARNING("Invalid statistic type %s", StatName.c_str());
			continue;
		}

		m_Manager->SetValue(StatType, (*it).asInt());
	}

	return true;
}