summaryrefslogtreecommitdiff
path: root/src/file/settings.cpp
blob: eb8ed5d8005fade3462378d9ec2ed1ba417e4594 (plain)
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
#include <fstream>

#include "settings.hpp"
#include "logger/logger_set.hpp"
#include "converter/file_to_struct.hpp"
#include "converter/struct_to_file.hpp"
#include "parser/settings.hpp"

namespace smtp::file
{

	//
	//Constructors
	//

	Settings::Settings( std::string const& path_file, checker::RegistratorSettings const& registrator_errors )
			: mPathFile( path_file )
			, mRegistratorErrors( registrator_errors )
	{

	}

	//
	//Public methods
	//

	manage::SettingsFields Settings::Read() const
	{
		auto parsed_store = GetParsedStore();
        return converter::FileToStruct{}.Convert( parsed_store );
	}

	bool Settings::Write( manage::SettingsFields const& settings_fields ) const
	{
        auto parsed_data = converter::StructToFile{}.Convert( settings_fields );
		return mRegistratorErrors.Check( parsed_data ) && SetParsedData( parsed_data );
	}

	//
	//Private methods
	//

	manage::SettingsFileDataType Settings::GetParsedStore() const
	{
		static const std::string METHOD_NAME = "Read settings";

		std::ifstream settings_file{mPathFile, std::fstream::in};
        if( !settings_file.is_open() )
		{
			logger::LoggerSet::GetInstance()->LogError( METHOD_NAME, "Unable to open file to read " + mPathFile );
			return {};
		}
		auto result = GetDataFromFile( settings_file );

		settings_file.close();
		return mRegistratorErrors.Check( result ) ? result : manage::SettingsFileDataType{};
	}

	manage::SettingsFileDataType Settings::GetDataFromFile( std::ifstream& settings_file ) const
	{
		std::string line{};
		manage::SettingsFileDataType result;

		while( std::getline( settings_file, line ))
		{
			auto parsed_data = parser::Settings{}.Parse( line );
			result.insert( parsed_data );
		}
		return result;
	}

	bool Settings::SetParsedData( manage::SettingsFileDataType const& parsed_data ) const
	{
		static const std::string METHOD_NAME = "Write settings";

		std::ofstream settings_file{mPathFile, std::fstream::out | std::fstream::trunc};
		if( !settings_file.is_open())
		{
			logger::LoggerSet::GetInstance()->LogError( METHOD_NAME, "Unable to open file to write " + mPathFile );
			return false;
		}
        for( const auto& data : parsed_data )
		{
			auto line = BuildParam( data );
			settings_file << line << "\n";
		}
		settings_file.close();
		return true;
	}

	std::string Settings::BuildParam( std::pair < std::string, std::string > const& data ) const
	{
		std::string result;
		result += data.first;
		result += '=';
		result += data.second;
		return result;
	}
}