~aleteoryx/muditaos

ref: d13f45b6ce5691457bd58ec97d996ec4b110b82f muditaos/module-apps/DatabaseModel.hpp -rw-r--r-- 1.8 KiB
d13f45b6 — jimmorrisson [EGD-4203] UTF8 smart pointers refactor (#938) 5 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
// Copyright (c) 2017-2020, 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 "Application.hpp"

namespace app
{

    template <class T> class DatabaseModel
    {
      protected:
        /// Pointer to application that owns the model
        Application *application = nullptr;
        uint32_t recordsCount    = 0;
        std::vector<std::shared_ptr<T>> records;
        uint32_t modelIndex = 0;

      public:
        DatabaseModel(Application *app) : application{app}, recordsCount{0}
        {}

        virtual ~DatabaseModel()
        {
            clear();
        }

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

            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_ERROR("Null pointer received from DB");
                return false;
            }
        }

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

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

            if (index >= records.size()) {
                return nullptr;
            }

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

            auto item = records[index];

            modelIndex++;

            return item;
        }
    };

} /* namespace app */