aboutsummaryrefslogtreecommitdiff
path: root/shared/src/commonMain/kotlin/mx/trackermap/TrackerMap/controllers/AttributesController.kt
blob: 6262ec885410a65c918a3e40ed026c44108b65fb (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
package mx.trackermap.TrackerMap.controllers

import mx.trackermap.TrackerMap.client.apis.AttributesApi
import mx.trackermap.TrackerMap.client.models.Attribute
import mx.trackermap.TrackerMap.client.models.Device

class AttributesController(
    private val attributesApi: AttributesApi,
    private val sessionController: SessionController)
{
    var userAttributes = emptyArray<Attribute>()
    val deviceAttributes = mutableMapOf<Int, Array<Attribute>>()

    /** userAttributes **/

    suspend fun getUserAttributes() {
        userAttributes = attributesApi.attributesComputedGet(userId = sessionController.user?.id)
    }

    fun getUserAttribute(attribute: String) = userAttributes.find { it.attribute == attribute }

    suspend fun createUserAttribute(attribute: Attribute) {
        userAttributes += attributesApi.attributesComputedPost(attribute)
    }

    suspend fun updateUserAttribute(attribute: Attribute) {
        userAttributes = userAttributes.map {
            if (attribute.id != null && it.id == attribute.id) {
                attributesApi.attributesComputedIdPut(attribute, attribute.id)
            } else it
        }.toTypedArray()
    }

    suspend fun deleteUserAttribute(attribute: String) {
        userAttributes.find { it.attribute == attribute }?.id?.let { id ->
            attributesApi.attributesComputedIdDelete(id)
            userAttributes = userAttributes.filter { it.id != id }.toTypedArray()
        }
    }

    /** deviceAttributes **/

    suspend fun getDeviceAttributes(device: Device) {
        device.id?.let {
            deviceAttributes[it] = attributesApi.attributesComputedGet(deviceId = device.id)
        }
    }

    fun getDeviceAttribute(device: Device, attribute: String) =
        deviceAttributes[device.id]?.find { it.attribute == attribute }

}