diff --git a/Modules/Sources/Browse/UI/Views/DownloadView.swift b/Modules/Sources/Browse/UI/Views/DownloadView.swift new file mode 100644 index 0000000..8a041ab --- /dev/null +++ b/Modules/Sources/Browse/UI/Views/DownloadView.swift @@ -0,0 +1,104 @@ +// +// DownloadView.swift +// Browse +// +// Created by Javier Cicchelli on 17/12/2022. +// Copyright © 2022 Röck+Cöde. All rights reserved. +// + +import DataModels +import Foundation +import KeychainStorage +import SwiftUI + +struct DownloadView: View { + + // MARK: Storages + + @KeychainStorage(key: .KeychainStorage.account) private var account: Account? + + // MARK: States + + @State private var data: Data? + + // MARK: Properties + + private let id: String + private let name: String + private let downloaded: ActionClosure + + private let getData: GetDataUseCase = .init() + + // MARK: Initialisers + + init( + id: String, + name: String, + data: Data? = nil, + downloaded: @escaping ActionClosure + ) { + self.id = id + self.name = name + self.downloaded = downloaded + + self._data = .init(initialValue: data) + } + + // MARK: Body + + var body: some View { + if let data { + SaveDocumentPicker( + fileName: name, + fileData: data + ) { error in + guard error == nil else { + // TODO: Handle this error case. + return + } + + downloaded() + } + } else { + LoadingView() + .task { + await loadData() + } + } + } + +} + +// MARK: - Helpers + +private extension DownloadView { + func loadData() async { + guard let account else { + // TODO: Handle this error case. + return + } + + do { + data = try await getData( + id: id, + username: account.username, + password: account.password + ) + } catch { + // TODO: Handle this error case. + } + } +} + +// MARK: - Previews + +struct DownloadView_Previews: PreviewProvider { + static var previews: some View { + DownloadView( + id: "1234567890", + name: "some-name.txt" + ) { + // Downloaded closure. + } + } +}