import Foundation

final class AudioPlayerSettings: ObservableObject, LocalizedItem {

    @Published
    var playlistCoverImageSize: Int

    @Published
    var smallCoverImageSize: Int

    @Published
    var audioPlayerJsFile: FileResource?

    @Published
    var audioPlayerCssFile: FileResource?

    @Published
    var german: LocalizedAudioPlayerSettings

    @Published
    var english: LocalizedAudioPlayerSettings

    init(playlistCoverImageSize: Int,
         smallCoverImageSize: Int,
         audioPlayerJsFile: FileResource?,
         audioPlayerCssFile: FileResource?,
         german: LocalizedAudioPlayerSettings,
         english: LocalizedAudioPlayerSettings) {
        self.playlistCoverImageSize = playlistCoverImageSize
        self.smallCoverImageSize = smallCoverImageSize
        self.audioPlayerJsFile = audioPlayerJsFile
        self.audioPlayerCssFile = audioPlayerCssFile
        self.german = german
        self.english = english
    }

    func remove(_ file: FileResource) {
        if audioPlayerJsFile == file {
            audioPlayerJsFile = nil
        }
        if audioPlayerCssFile == file {
            audioPlayerCssFile = nil
        }
    }
}

// MARK: Storage

extension AudioPlayerSettings {

    convenience init(context: LoadingContext, data: Data) {
        self.init(
            playlistCoverImageSize: data.playlistCoverImageSize,
            smallCoverImageSize: data.smallCoverImageSize,
            audioPlayerJsFile: data.audioPlayerJsFile.map(context.file),
            audioPlayerCssFile: data.audioPlayerCssFile.map(context.file),
            german: .init(data: data.german),
            english: .init(data: data.english))
    }

    var data: Data {
        .init(playlistCoverImageSize: playlistCoverImageSize,
              smallCoverImageSize: smallCoverImageSize,
              audioPlayerJsFile: audioPlayerJsFile?.identifier,
              audioPlayerCssFile: audioPlayerCssFile?.identifier,
              german: german.data,
              english: english.data)
    }

    struct Data: Codable, Equatable {
        let playlistCoverImageSize: Int
        let smallCoverImageSize: Int
        let audioPlayerJsFile: String?
        let audioPlayerCssFile: String?
        let german: LocalizedAudioPlayerSettings.Data
        let english: LocalizedAudioPlayerSettings.Data
    }


}
