summaryrefslogtreecommitdiff
path: root/src/file/mail.cpp
blob: a7e30eab53a9fcef84399e7110e8995e99f8eec6 (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
#include <fstream>

#include "mail.hpp"
#include "logger/logger_set.hpp"

namespace smtp::file
{

    //
    //Constructors
    //

    Mail::Mail( std::string const& path_file, checker::RegistratorMails const& registrator_errors )
        : mPathFile( path_file )
		, mRegistratorErrors( registrator_errors )
    {
    }

    //
    //Public methods
    //

    manage::MailsSet Mail::Read() const
    {
		static const std::string METHOD_NAME = "Read mails";

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

        auto result = ReadFile( mail_file );

        mail_file.close();
        return result;
    }

    bool Mail::Write( manage::MailsSet const& data ) const
    {
		static const std::string METHOD_NAME = "Write mails";

        std::ofstream mail_file{ mPathFile, std::fstream::out | std::fstream::trunc };


        if ( !mail_file.is_open() )
        {
			logger::LoggerSet::GetInstance()->LogError( METHOD_NAME, "Unable to open file to write " + mPathFile );
            return false;
        }

        auto result = WriteFile( mail_file, data );

        mail_file.close();
        return result;
    }

    //
    //Private methods
    //

    manage::MailsSet Mail::ReadFile( std::ifstream& mail_file ) const
    {
        std::string line{};
        manage::MailsSet result;

        while ( std::getline( mail_file, line ) )
        {
            if( mRegistratorErrors.Check( line ) )
            {
                result.push_back( line );
            }
        }
        return result;
    }

    bool Mail::WriteFile( std::ofstream& mail_file, manage::MailsSet const& data ) const
    {
        bool result = true;
        for( const auto& mail : data )
        {
            if( mRegistratorErrors.Check( mail ) )
            {
                mail_file << mail << "\n";
            }
            else
            {
                result = false;
            }
        }
        return result;
    }
}