import Foundation

final class PostSettings: ObservableObject, LocalizedItem {

    /// The number of posts to show in a single page of the news feed
    @Published
    var postsPerPage: Int

    /// The maximum width of the main content
    @Published
    var contentWidth: Int

    @Published
    var swiperCssFile: FileResource?

    @Published
    var swiperJsFile: FileResource?

    @Published
    var defaultCssFile: FileResource?

    @Published
    var german: LocalizedPostSettings

    @Published
    var english: LocalizedPostSettings

    init(postsPerPage: Int,
         contentWidth: Int,
         swiperCssFile: FileResource?,
         swiperJsFile: FileResource?,
         defaultCssFile: FileResource?,
         german: LocalizedPostSettings,
         english: LocalizedPostSettings) {
        self.postsPerPage = postsPerPage
        self.contentWidth = contentWidth
        self.swiperCssFile = swiperCssFile
        self.swiperJsFile = swiperJsFile
        self.defaultCssFile = defaultCssFile
        self.german = german
        self.english = english
    }

    func remove(_ file: FileResource) {
        if swiperJsFile == file {
            swiperJsFile = nil
        }
        if swiperCssFile == file {
            swiperCssFile = nil
        }
        if defaultCssFile == file {
            defaultCssFile = nil
        }
    }
}

// MARK: Storage

extension PostSettings {

    convenience init(context: LoadingContext, data: Data) {
        self.init(
            postsPerPage: data.postsPerPage,
            contentWidth: data.contentWidth,
            swiperCssFile: data.swiperCssFile.map(context.file),
            swiperJsFile: data.swiperJsFile.map(context.file),
            defaultCssFile: data.defaultCssFile.map(context.file),
            german: .init(context: context, data: data.german),
            english: .init(context: context, data: data.english))
    }

    var data: PostSettings.Data {
        .init(postsPerPage: postsPerPage,
              contentWidth: contentWidth,
              swiperCssFile: swiperCssFile?.identifier,
              swiperJsFile: swiperJsFile?.identifier,
              defaultCssFile: defaultCssFile?.identifier,
              german: german.data,
              english: english.data)
    }

    struct Data: Codable, Equatable {
        let postsPerPage: Int
        let contentWidth: Int
        let swiperCssFile: String?
        let swiperJsFile: String?
        let defaultCssFile: String?
        let german: LocalizedPostSettings.Data
        let english: LocalizedPostSettings.Data
    }
}
