import Foundation

final class LocalizedTag: ChangeObservingItem {

    @Published
    var urlComponent: String

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

    @Published
    var linkPreview: LinkPreview

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

    init(content: Content,
         urlComponent: String,
         name: String,
         linkPreview: LinkPreview = .init(),
         originalUrl: String? = nil) {
        self.urlComponent = urlComponent
        self.name = name
        self.linkPreview = linkPreview
        self.originalUrl = originalUrl
        super.init(content: content)
    }

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

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

// MARK: Storage

extension LocalizedTag {

    convenience init(context: LoadingContext, data: Data) {
        self.init(
            content: context.content,
            urlComponent: data.urlComponent,
            name: data.name,
            linkPreview: .init(context: context, data: data.linkPreview),
            originalUrl: data.originalUrl)
    }

    struct Data: Codable, Equatable {
        let urlComponent: String
        let name: String
        let linkPreview: LinkPreview.Data
        let originalUrl: String?
    }

    var data: Data {
        .init(urlComponent: urlComponent,
              name: name,
              linkPreview: linkPreview.data,
              originalUrl: originalUrl)
    }
}
