import Foundation

final class Tag: Item {

    @Published
    var isVisible: Bool

    @Published
    var german: LocalizedTag

    @Published
    var english: LocalizedTag

    override init(content: Content, id: String) {
        self.isVisible = true
        self.english = .init(content: content, urlComponent: id, name: id)
        let deId = id + "-" + ContentLanguage.german.rawValue
        self.german = .init(content: content, urlComponent: deId, name: deId)
        super.init(content: content, id: id)
    }

    init(content: Content, id: String, isVisible: Bool = true, german: LocalizedTag, english: LocalizedTag) {
        self.isVisible = isVisible
        self.german = german
        self.english = english
        super.init(content: content, id: id)
    }

    func isValid(id: String) -> Bool {
        content.isValidIdForTagOrPageOrPost(id) &&
        content.isNewIdForTag(id)
    }

    @discardableResult
    func update(id newId: String) -> Bool {
        guard content.storage.move(tag: id, to: newId) else {
            print("Failed to move files of tag \(id)")
            return false
        }
        id = newId
        return true
    }

    // MARK: Paths

    func filePathRelativeToOutputFolder(for language: ContentLanguage) -> String {
        makeCleanRelativePath(internalPath(for: language))
    }

    private func internalPath(for language: ContentLanguage) -> String {
        content.settings.paths.tagsOutputFolderPath + "/" + localized(in: language).urlComponent
    }

    override func absoluteUrl(in language: ContentLanguage) -> String {
        makeCleanAbsolutePath(internalPath(for: language))
    }

    override func title(in language: ContentLanguage) -> String {
        localized(in: language).title
    }

    override var itemType: ItemType {
        .tagPage(self)
    }

    func contains(urlComponent: String) -> Bool {
        german.urlComponent == urlComponent || english.urlComponent == urlComponent
    }
}

extension Tag: LocalizedItem {

}

extension Tag {

    var file: TagFile {
        .init(id: id,
              isVisible: isVisible,
              german: german.tagFile,
              english: english.tagFile)
    }
}
