aboutsummaryrefslogtreecommitdiff
path: root/Hutch/App/AppConfiguration.swift
blob: c733799ad978417696d14b7e1203150238d01ef9 (plain) (blame)
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
import Foundation

struct AppConfiguration: Sendable {
    static let defaultHutchStatsBaseURL = HutchStatsAPI.defaultBaseURL
    static let hutchStatsBaseURLEnvironmentKey = "HUTCH_STATS_BASE_URL"

    let hutchStatsBaseURL: URL

    init(
        userDefaults: UserDefaults = .standard,
        processInfo: ProcessInfo = .processInfo,
        environment: [String: String]? = nil
    ) {
        let resolvedEnvironment = environment ?? processInfo.environment

        if
            let rawValue = resolvedEnvironment[Self.hutchStatsBaseURLEnvironmentKey],
            let url = Self.normalizedURL(from: rawValue)
        {
            self.hutchStatsBaseURL = url
        } else if
            let rawValue = userDefaults.string(forKey: AppStorageKeys.hutchStatsBaseURL),
            let url = Self.normalizedURL(from: rawValue)
        {
            self.hutchStatsBaseURL = url
        } else {
            self.hutchStatsBaseURL = Self.defaultHutchStatsBaseURL
        }
    }

    private static func normalizedURL(from rawValue: String) -> URL? {
        guard var components = URLComponents(string: rawValue.trimmingCharacters(in: .whitespacesAndNewlines)) else {
            return nil
        }

        if components.path.isEmpty {
            components.path = "/"
        }

        return components.url
    }
}