aboutsummaryrefslogtreecommitdiff
path: root/iosApp/iosApp/Units/UnitsViewModel.swift
blob: 648e429c4763c2d409382dba7dc38efbe066a124 (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
//
//  UnitsViewModel.swift
//  iosApp
//
//  Created by Iván on 28/01/22.
//  Copyright © 2022 orgName. All rights reserved.
//

import Foundation
import shared

class UnitsViewModel: ObservableObject {
    @Inject var unitsController: UnitsController
    @Inject var geofenceController: GeofencesController
    
    enum UnitsDisplayMode {
        case map
        case list
    }
    
    @Published var searchQuery = "" {
        didSet {
            unitsDisplayMode = .list
            search(query: searchQuery)
        }
    }
    @Published var isEditing = false
    @Published var unitsDisplayMode: UnitsDisplayMode = .list
    @Published var units: [UnitInformation] = []
    @Published var selectedUnit: UnitInformation? = nil
    @Published var geofences: [Int: Geofence] = [:]
    
    init() {
        setupObservers()
    }
    
    private func setupObservers() {
        let unitsCollector = Collector<[UnitInformation]>(callback: setUnits)
        unitsController.displayedUnitsFlow.collect(collector: unitsCollector) { unit, error in }
        
        let geofencesCollector = Collector<[Int: Geofence]>(callback: setGeofences)
        geofenceController.geofencesFlow.collect(collector: geofencesCollector) { unit, error in }
    }
    
    private func setUnits(units: [UnitInformation]) {
        self.units = units
    }
    
    private func setGeofences(geofences: [Int: Geofence]) {
        self.geofences = geofences
    }
    
    func toggleDisplayMode() {
        switch unitsDisplayMode {
        case .map:
            unitsDisplayMode = .list
        case .list:
            unitsDisplayMode = .map
        }
    }
    
    func search(query: String) {
        unitsController.search(query: query)
    }
}