import AppKit
import Foundation
import UniformTypeIdentifiers

enum WeblocFileWriter {
    static func writeWebloc(at fileURL: URL, destinationURL: URL) throws {
        let plist: [String: Any] = ["URL": destinationURL.absoluteString]
        let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
        try data.write(to: fileURL, options: .atomic)
    }
}

enum DesktopWeblocShortcutPresenter {
    static func beginSavePanel(forAppNamed name: String, webURL: URL) {
        let panel = NSSavePanel()
        panel.title = "Add to desktop"
        panel.message = "Choose where to save the web shortcut."
        panel.nameFieldStringValue = sanitizedFileName(name) + ".webloc"
        panel.canCreateDirectories = false
        if let weblocType = UTType(filenameExtension: "webloc") {
            panel.allowedContentTypes = [weblocType]
        }
        if let desktop = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first {
            panel.directoryURL = desktop
        }
        panel.begin { response in
            guard response == .OK, let dest = panel.url else { return }
            do {
                try WeblocFileWriter.writeWebloc(at: dest, destinationURL: webURL)
            } catch {
                DispatchQueue.main.async {
                    let alert = NSAlert()
                    alert.messageText = "Couldn’t save shortcut"
                    alert.informativeText = error.localizedDescription
                    alert.alertStyle = .warning
                    alert.runModal()
                }
            }
        }
    }

    private static func sanitizedFileName(_ name: String) -> String {
        let trimmed = name
            .replacingOccurrences(of: "/", with: "-")
            .replacingOccurrences(of: ":", with: "-")
            .trimmingCharacters(in: .whitespacesAndNewlines)
        return trimmed.isEmpty ? "Shortcut" : trimmed
    }
}
