~aleteoryx/muditaos

muditaos/module-apps/apps-common/DatabaseModel.hpp -rw-r--r-- 2.1 KiB
a405cad6Aleteoryx trim readme 6 days 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
// Copyright (c) 2017-2024, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/blob/master/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()) {
                LOG_INFO("DB is empty");
                return false;
            }

            for (const auto &dbRecord : dbRecords) {
                records.push_back(std::make_shared<T>(dbRecord));
            }
            return true;
        }

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

        std::shared_ptr<T> getRecord(gui::Order order)
        {
            int index = 0;

            switch (order) {
            case gui::Order::Next:
                index = modelIndex;
                modelIndex++;
                break;

            case gui::Order::Previous:
                index = records.size() - 1 + modelIndex;
                modelIndex--;
                break;

            default:
                break;
            }

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

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