import Foundation
import SwiftUI

final class GeneralSettings: ObservableObject {

    @AppStorage("pushNotificationAccessToken")
    var pushNotificationAccessToken: String?

    @Published
    var url: String

    @Published
    var linkPreviewImageWidth: Int

    @Published
    var linkPreviewImageHeight: Int

    @Published
    var remoteUserForUpload: String

    @Published
    var remotePortForUpload: Int

    @Published
    var remotePathForUpload: String

    @Published
    var urlForPushNotification: String?

    @Published
    var requiredFiles: [FileResource]

    init(url: String, linkPreviewImageWidth: Int, linkPreviewImageHeight: Int, remoteUserForUpload: String, remotePortForUpload: Int, remotePathForUpload: String, urlForPushNotification: String?, requiredFiles: [FileResource]) {
        self.url = url
        self.linkPreviewImageWidth = linkPreviewImageWidth
        self.linkPreviewImageHeight = linkPreviewImageHeight
        self.remoteUserForUpload = remoteUserForUpload
        self.remotePortForUpload = remotePortForUpload
        self.remotePathForUpload = remotePathForUpload
        self.urlForPushNotification = urlForPushNotification
        self.requiredFiles = requiredFiles
    }
}

extension GeneralSettings {

    convenience init(context: LoadingContext, data: Data) {
        self.init(
            url: data.url,
            linkPreviewImageWidth: data.linkPreviewImageWidth,
            linkPreviewImageHeight: data.linkPreviewImageHeight,
            remoteUserForUpload: data.remoteUserForUpload,
            remotePortForUpload: data.remotePortForUpload,
            remotePathForUpload: data.remotePathForUpload,
            urlForPushNotification: data.urlForPushNotification,
            requiredFiles: data.requiredFiles?.compactMap(context.file) ?? [])
    }

    var data: Data {
        .init(
            url: url,
            linkPreviewImageWidth: linkPreviewImageWidth,
            linkPreviewImageHeight: linkPreviewImageHeight,
            remoteUserForUpload: remoteUserForUpload,
            remotePortForUpload: remotePortForUpload,
            remotePathForUpload: remotePathForUpload,
            urlForPushNotification: urlForPushNotification,
            requiredFiles: requiredFiles.nonEmpty?.map { $0.identifier }.sorted())
    }

    struct Data: Codable, Equatable {
        let url: String
        let linkPreviewImageWidth: Int
        let linkPreviewImageHeight: Int
        let remoteUserForUpload: String
        let remotePortForUpload: Int
        let remotePathForUpload: String
        let urlForPushNotification: String?
        let requiredFiles: [String]?
    }
}
