import AppKit
import Quartz
import UniformTypeIdentifiers

/// F3: mostra il file in una finestra. Esc, F3 o Q la chiudono.
final class ViewerWindowController: NSWindowController, NSWindowDelegate {
    private static var open: [ViewerWindowController] = []

    static func show(_ url: URL) {
        let vc = ViewerWindowController(url: url)
        open.append(vc)
        vc.showWindow(nil)
        vc.window?.makeKeyAndOrderFront(nil)
    }

    private init(url: URL) {
        let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 760),
                         styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false)
        w.title = url.lastPathComponent
        w.isReleasedWhenClosed = false
        w.setFrameAutosaveName("Visualizzatore")
        super.init(window: w)
        w.delegate = self
        w.contentView = ViewerWindowController.contentView(for: url)
        if !w.setFrameUsingName("Visualizzatore") { w.center() }
    }

    required init?(coder: NSCoder) { fatalError() }

    func windowWillClose(_ notification: Notification) {
        ViewerWindowController.open.removeAll { $0 === self }
    }

    func handleKey(_ e: NSEvent) -> Bool {
        let mods = e.modifierFlags.intersection([.control, .option, .command, .shift])
        if e.keyCode == KeyCode.escape || e.keyCode == KeyCode.f3 || (mods.isEmpty && e.charactersIgnoringModifiers == "q") {
            close()
            return true
        }
        return false
    }

    private static func contentView(for url: URL) -> NSView {
        let type = UTType(filenameExtension: url.pathExtension)
        let rich: [UTType] = [.image, .pdf, .audiovisualContent, .rtf, .html, .rtfd]
        if let type, rich.contains(where: { type.conforms(to: $0) }) {
            return quickLook(url)
        }
        if let text = readText(url) { return textView(text) }
        return quickLook(url)
    }

    private static func quickLook(_ url: URL) -> NSView {
        let v = QLPreviewView(frame: .zero, style: .normal)!
        v.previewItem = url as NSURL
        return v
    }

    /// Testo come nel Lister di TC: anche file senza estensione o con estensioni sconosciute.
    private static func readText(_ url: URL) -> String? {
        guard let h = try? FileHandle(forReadingFrom: url) else { return nil }
        defer { try? h.close() }
        let data = (try? h.read(upToCount: 4 * 1024 * 1024)) ?? Data()
        if data.prefix(8192).contains(0) { return nil }
        return String(data: data, encoding: .utf8) ?? String(data: data, encoding: .windowsCP1252)
    }

    private static func textView(_ text: String) -> NSView {
        let scroll = NSTextView.scrollableTextView()
        let tv = scroll.documentView as! NSTextView
        tv.isEditable = false
        tv.font = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
        tv.textColor = Theme.text
        tv.backgroundColor = Theme.background
        tv.string = text
        return scroll
    }
}
