import Foundation

final class LocalizedTag: ObservableObject {

    unowned let content: Content

    @Published
    var urlComponent: String

    /// A custom name, different from the tag id
    @Published
    var name: String

    @Published
    var linkPreviewTitle: String?

    @Published
    var linkPreviewDescription: String?

    /// The image id of the thumbnail
    @Published
    var linkPreviewImage: FileResource?

    /// The original url in the previous site layout
    let originalUrl: String?

    init(content: Content,
         urlComponent: String,
         name: String,
         linkPreviewTitle: String? = nil,
         linkPreviewDescription: String? = nil,
         linkPreviewImage: FileResource? = nil,
         originalUrl: String? = nil) {
        self.content = content
        self.urlComponent = urlComponent
        self.name = name
        self.linkPreviewTitle = linkPreviewTitle
        self.linkPreviewDescription = linkPreviewDescription
        self.linkPreviewImage = linkPreviewImage
        self.originalUrl = originalUrl
    }

    func isValid(urlComponent: String) -> Bool {
        content.isValidIdForTagOrPageOrPost(urlComponent) &&
        !content.containsTag(withUrlComponent: urlComponent)
    }

    /// The title to display when considering multiple items of this tag
    var title: String {
        linkPreviewTitle ?? name
    }
}

extension LocalizedTag: LinkPreviewItem {

}

extension LocalizedTag {

    var tagFile: LocalizedTagFile {
        .init(urlComponent: urlComponent,
              name: name,
              linkPreviewTitle: linkPreviewTitle,
              linkPreviewDescription: linkPreviewDescription,
              linkPreviewImage: linkPreviewImage?.id,
              originalURL: originalUrl)
    }
}
