aboutsummaryrefslogtreecommitdiff
path: root/iosApp/iosApp/Units/UnitsViewModel.swift
blob: b12291ee3c0c687810d4024152a1efee54d10ca9 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/**
 * TrackerMap
 * Copyright (C) 2021-2022  Iván Ávalos <avalos@disroot.org>, Henoch Ojeda <imhenoch@protonmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
import Foundation
import WhirlyGlobe
import shared

@MainActor
class UnitsViewModel: ObservableObject {
    @Inject var networkController: NetworkController
    @Inject var unitsController: UnitsController
    @Inject var geofenceController: GeofencesController
    
    let mainScope = MainScope.companion.createMainScope()
    
    enum UnitsDisplayMode {
        case map
        case list
    }
    
    var detailsUnit: UnitInformation? = nil
    var detailsAction = DeviceRow.Action.details
    
    @Published var networkAvailable: Bool? = nil
    @Published var searchQuery = "" {
        didSet {
            unitsDisplayMode = .list
            search(query: searchQuery)
        }
    }
    @Published var isEditing = false
    @Published var showDetails = false
    @Published var showUserInfo = false
    @Published var unitsDisplayMode: UnitsDisplayMode = .map
    @Published var units: [UnitInformation] = [] {
        didSet {
            Task { @MainActor in
                markers = units.compactMap(Marker.companion.fromUnit)
            }
        }
    }
    @Published var markers: [Marker] = []
    @Published var oldSelectedUnit: UnitInformation? = nil
    @Published var selectedUnit: UnitInformation? = nil {
        didSet {
            if selectedUnit?.device.id != oldSelectedUnit?.device.id {
                if let unit = selectedUnit {
                    selectedMarker = Marker.companion.fromUnit(unit: unit)
                } else {
                    selectedMarker = nil
                }
            }
        }
    }
    @Published var selectedMarker: Marker? = nil
    @Published var mapLayerType: MapLayer = .companion.defaultLayer
    @Published var geofences: [Int: Geofence] = [:] {
        didSet {
            flatGeofences = Array(geofences.values)
        }
    }
    @Published var flatGeofences: [Geofence] = []
    
    init() {
        unitsController.fetchUnits(scope: mainScope)
        setupObservers()
    }
    
    deinit {
        MainScope.companion.cancelScope(scope: mainScope)
    }
    
    private func setupObservers() {
        let networkCollector = Collector<Bool?>(callback: setNetworkState)
        networkController.networkAvailable.collect(collector: networkCollector) { _ in }
        
        let unitsCollector = Collector<[UnitInformation]>(callback: setUnits)
        unitsController.displayedUnitsFlow.collect(collector: unitsCollector) { _ in }
        
        let geofencesCollector = Collector<[Int: Geofence]>(callback: setGeofences)
        geofenceController.geofencesFlow.collect(collector: geofencesCollector) { _ in }
    }
    
    private func setNetworkState(state: Bool?) {
        print("Network state is: \(state?.description ?? "")")
        Task { @MainActor in
            self.networkAvailable = state
        }
    }
    
    private func setUnits(units: [UnitInformation]) {
        print("Positions")
        Task { @MainActor in
            self.units = units
        }
        updateSelectedUnit()
    }
    
    private func setGeofences(geofences: [Int: Geofence]) {
        Task { @MainActor in
            self.geofences = geofences
        }
    }
    
    func selectUnit(unit: UnitInformation?, switchToMap: Bool = true) {
        print ("Selecting unit \(unit?.device.name ?? "")")
        oldSelectedUnit = selectedUnit
        selectedUnit = unit
        if unit != nil && switchToMap {
            setDisplayMode(UnitsDisplayMode.map)
        }
    }
    
    func selectUnitWith(position id: Int32?, switchToMap: Bool = true) {
        if id == nil {
            print("Deselecting unit")
            selectUnit(unit: nil, switchToMap: switchToMap)
            return
        }
        print("Selecting unit with position id: \(id!)")
        let unit = units.first {
            Int32(truncating: $0.position?.id ?? 0) == id!
        }
        selectUnit(unit: unit, switchToMap: switchToMap)
    }
    
    private func selectUnitWith(id: Int32?, switchToMap: Bool = true) {
        if id == nil {
            print("Deselecting unit")
            selectUnit(unit: nil, switchToMap: switchToMap)
            return
        }
        print("Selecting unit with device id: \(id!)")
        let unit = units.first {
            $0.device.id == id!
        }
        selectUnit(unit: unit, switchToMap: switchToMap)
    }
    
    private func updateSelectedUnit() {
        if let selected = selectedUnit {
            print("Updating selected unit with id: \(selected.device.id)")
            selectUnitWith(id: selected.device.id, switchToMap: false)
        }
    }
    
    func setDisplayMode(_ displayMode: UnitsDisplayMode) {
        unitsDisplayMode = displayMode
    }
    
    func toggleDisplayMode() {
        switch unitsDisplayMode {
        case .map:
            setDisplayMode(.list)
        case .list:
            setDisplayMode(.map)
        }
    }
    
    func search(query: String) {
        unitsController.search(query: query)
    }
    
    func show(action: DeviceRow.Action, for unit: UnitInformation) {
        if action != .close {
            detailsAction = action
            detailsUnit = unit
            showDetails = true
        } else {
            selectedUnit = nil
        }
    }
}