summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/View controllers/SelectLocation/LocationDataSourceProtocol.swift
blob: 79f78ebc994370f390e31c879983347a208a1eb4 (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
//
//  LocationDataSourceProtocol.swift
//  MullvadVPN
//
//  Created by Mojgan on 2024-02-07.
//  Copyright © 2024 Mullvad VPN AB. All rights reserved.
//

import Foundation
import MullvadREST
import MullvadTypes

protocol LocationDataSourceProtocol {
    var nodes: [LocationNode] { get }
    var searchableNodes: [LocationNode] { get }
}

extension LocationDataSourceProtocol {
    func search(by text: String) -> [LocationNode] {
        guard !text.isEmpty else {
            resetNodes()
            return nodes
        }

        var filteredNodes: [LocationNode] = []

        searchableNodes.forEach { countryNode in
            countryNode.showsChildren = false

            if countryNode.name.fuzzyMatch(text) {
                filteredNodes.append(countryNode)
            }

            countryNode.children.forEach { cityNode in
                cityNode.showsChildren = false
                cityNode.isHiddenFromSearch = true

                var relaysContainSearchString = false
                cityNode.children.forEach { hostNode in
                    hostNode.isHiddenFromSearch = true

                    if hostNode.name.fuzzyMatch(text) {
                        relaysContainSearchString = true
                        hostNode.isHiddenFromSearch = false
                    }
                }

                if cityNode.name.fuzzyMatch(text) || relaysContainSearchString {
                    if !filteredNodes.contains(countryNode) {
                        filteredNodes.append(countryNode)
                    }

                    countryNode.showsChildren = true
                    cityNode.isHiddenFromSearch = false

                    if relaysContainSearchString {
                        cityNode.showsChildren = true
                    }
                }
            }
        }

        return filteredNodes
    }

    private func resetNodes() {
        nodes.forEach { node in
            node.showsChildren = false
            node.isHiddenFromSearch = false

            node.forEachDescendant { descendantNode in
                descendantNode.showsChildren = false
                descendantNode.isHiddenFromSearch = false
            }
        }
    }
}