summaryrefslogtreecommitdiff
path: root/src/file/settings/file_decorator.cpp
blob: 1b05f724d9b1af09bddb6a23355a6702a2bcca57 (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
#include <fstream>

#include "file_decorator.hpp"
#include "logger/logger_set.hpp"
#include "parser.hpp"
#include "converter/file_to_string.hpp"

namespace smtp::file::settings
{

	//
	//Constructors
	//

    FileDecorator::FileDecorator( std::string const& path_file, errors::Registrator const& registrator_errors )
			: mPathFile( path_file )
            , mRegistratorErrors( registrator_errors )
	{

	}

	//
	//Public methods
	//

    general::SettingsFileDataType FileDecorator::Read() const
	{
        static const std::string METHOD_NAME = "Read settings";

        std::ifstream settings_file{mPathFile, std::fstream::in};
        if( !settings_file.is_open() )
        {
            mRegistratorErrors.Process( errors::types::SettingsType::Server );
            return {};
        }
        auto result = GetDataFromFile( settings_file );

        settings_file.close();
        return result;
	}

    bool FileDecorator::Write( general::SettingsFileDataType const& 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;
        }
        auto settings_as_list = converter::FileToString{}.Convert(data);
        for( const auto& settings_as_string : settings_as_list )
        {
            settings_file << settings_as_string << "\n";
        }
        settings_file.close();
        return true;
	}

	//
	//Private methods
	//

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

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