import SwiftUI


struct TagDetailView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @EnvironmentObject
    private var selection: SelectedContent

    @ObservedObject
    var tag: Tag

    private var transferImage: (language: ContentLanguage, image: FileResource)? {
        tag.localized(in: language.next).linkPreview.image.map { (language.next, $0) }
    }

    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                DetailTitle(
                    title: "Tag",
                    text: "A tag groups posts and pages together based on a common theme.")

                BoolPropertyView(
                    title: "Appears in overviews",
                    value: $tag.isVisible,
                    footer: "Indicate if the tag should appear in the tag list of posts and pages. If the tag is not visible, then it can still be used as a filter.")

                IdPropertyView(
                    id: $tag.identifier,
                    title: "Tag id",
                    footer: "The unique id of the tag for references",
                    validation: tag.isValid) {
                        tag.update(id: $0)
                    }
                    .id(tag.id)

                LocalizedTagDetailView(
                    tag: tag.localized(in: language),
                    transferImage: transferImage)
                .id(tag.identifier + language.rawValue)
                ColoredButton(delete: deleteTag)
            }
            .padding()
        }
    }

    private func deleteTag() {
        guard content.storage.delete(tag: tag.identifier) else {
            print("Tag '\(tag.identifier)': Failed to delete file in content folder")
            return
        }
        content.remove(tag)
        selection.remove(tag)
    }
}

extension TagDetailView: MainContentView {

    init(item: Tag) {
        self.tag = item
    }

    static let itemDescription = "a tag"
}
