~aleteoryx/muditaos

ref: 1340e6949c0762585b0de844863c91c859fb19b1 muditaos/module-apps/apps-common/DatabaseModel.hpp -rw-r--r-- 2.1 KiB
1340e694 — Bartosz Revert "[MOS-578] Fix incorrect logic with SMS notifications" 2 years ago
                                                                                
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
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#pragma once

#include <module-gui/gui/widgets/ListItemProvider.hpp>
#include <cstdint>
#include <vector>
#include <utility>
#include <algorithm>

#include <apps-common/ApplicationCommon.hpp>

namespace app
{

    template <class T>
    class DatabaseModel
    {
      protected:
        ApplicationCommon *application = nullptr;
        unsigned int recordsCount      = std::numeric_limits<unsigned int>::max();
        int modelIndex                 = 0;
        std::vector<std::shared_ptr<T>> records;

      public:
        explicit DatabaseModel(ApplicationCommon *app) : application{app}
        {}

        virtual ~DatabaseModel()
        {
            clear();
        }

        virtual bool updateRecords(std::vector<T> dbRecords)
        {
            modelIndex = 0;
            records.clear();

            assert(dbRecords.size() <= recordsCount);

            if (!dbRecords.empty()) {
                for (uint32_t i = 0; i < dbRecords.size(); i++) {
                    records.push_back(std::make_shared<T>(dbRecords[i]));
                }

                return true;
            }
            else {
                LOG_WARN("DB is empty");
                return false;
            }
        }

        void clear()
        {
            records.clear();
            recordsCount = 0;
        }

        std::shared_ptr<T> getRecord(gui::Order order)
        {
            auto index = 0;
            if (order == gui::Order::Next) {
                index = modelIndex;

                modelIndex++;
            }
            else if (order == gui::Order::Previous) {
                index = records.size() - 1 + modelIndex;

                modelIndex--;
            }

            if (isIndexValid(index)) {
                return records[index];
            }
            else {
                return nullptr;
            }
        }

        [[nodiscard]] bool isIndexValid(unsigned int index) const noexcept
        {
            return index < records.size();
        }
    };

} /* namespace app */