//
//  GalleryFallbackViewController.swift
//  Tusker
//
//  Created by Shadowfacts on 5/16/23.
//  Copyright © 2023 Shadowfacts. All rights reserved.
//

import UIKit
import QuickLook
import Pachyderm

class GalleryFallbackViewController: QLPreviewController {
    
    private let attachment: Attachment
    private let previewItem: GalleryPreviewItem
    
    private var loadAttachmentTask: Task<Void, Never>?
    
    deinit {
        loadAttachmentTask?.cancel()
    }
    
    init(attachment: Attachment) {
        self.attachment = attachment
        self.previewItem = GalleryPreviewItem()
        
        super.init(nibName: nil, bundle: nil)
        
        dataSource = self
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if previewItem.previewItemURL == nil,
           loadAttachmentTask == nil {
            loadAttachmentTask = Task {
                do {
                    let (data, _) = try await URLSession.shared.data(from: attachment.url)
                    let url = FileManager.default.temporaryDirectory.appendingPathComponent(attachment.url.lastPathComponent)
                    try data.write(to: url)
                    try Task.checkCancellation()
                    previewItem.previewItemURL = url
                    refreshCurrentPreviewItem()
                } catch {
                    return
                }
            }
        }
    }
    
}

extension GalleryFallbackViewController: QLPreviewControllerDataSource {
    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }
    
    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
        return previewItem
    }
}

private class GalleryPreviewItem: NSObject, QLPreviewItem {
    var previewItemURL: URL? = nil
}
