summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/View controllers/SelectLocation/CustomListLocationNodeBuilder.swift
blob: dddebc6f6a1ca4925542b6b89334ed181d5a2071 (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
//
//  CustomListLocationNodeBuilder.swift
//  MullvadVPN
//
//  Created by Mojgan on 2024-03-14.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import Foundation
import MullvadSettings
import MullvadTypes

struct CustomListLocationNodeBuilder {
    let customList: CustomList
    let allLocations: [LocationNode]

    var customListLocationNode: CustomListLocationNode {
        let listNode = CustomListLocationNode(
            name: customList.name,
            code: customList.name,
            locations: customList.locations,
            isActive: true,  // Defaults to true, updated after children have been populated.
            customList: customList
        )

        listNode.children = listNode.locations.compactMap { location in
            let rootNode = RootLocationNode(children: allLocations)

            return switch location {
            case let .country(countryCode):
                rootNode
                    .countryFor(code: countryCode)?
                    .copy(withParent: listNode)

            case let .city(countryCode, cityCode):
                rootNode
                    .countryFor(code: countryCode)?
                    .cityFor(codes: [countryCode, cityCode])?
                    .copy(withParent: listNode)

            case let .hostname(countryCode, cityCode, hostCode):
                rootNode
                    .countryFor(code: countryCode)?
                    .cityFor(codes: [countryCode, cityCode])?
                    .hostFor(code: hostCode)?
                    .copy(withParent: listNode)
            }
        }

        listNode.isActive = !listNode.children.isEmpty
        listNode.sort()

        return listNode
    }
}

private extension CustomListLocationNode {
    func sort() {
        let sortedChildren = Dictionary(
            grouping: children,
            by: {
                return switch RelayLocation(dashSeparatedString: $0.code)! {
                case .country:
                    LocationGroup.country
                case .city:
                    LocationGroup.city
                case .hostname:
                    LocationGroup.host
                }
            }
        )
        .sorted(by: { $0.key < $1.key })
        .reduce([]) {
            $0 + $1.value.sorted(by: { $0.name < $1.name })
        }

        children = sortedChildren
    }
}

private enum LocationGroup: CaseIterable, Comparable {
    case country, city, host
}