//
//  KMHistoryFileCollectionViewItem.swift
//  PDF Reader Pro
//
//  Created by wanjun on 2022/10/28.
//

import Cocoa
import QuickLook

class KMHistoryFileCollectionViewItem: NSCollectionViewItem {

    @IBOutlet weak var mainBox: KMBox!
    @IBOutlet weak var imageBox: NSBox!
    @IBOutlet weak var fileImageView: NSImageView!
    @IBOutlet weak var favoriteButton: NSButton!
    @IBOutlet weak var documentName: NSTextField!
    
    var filePathUrl: URL? = nil
    var selectUrls: [URL] = []
    var isSelect: Bool = false
    var currentWindowController: NSWindowController?

    // MARK: init
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
        initializeUI()
        mainBox.menu = tableCellMenu
        mainBox.canDoubleClick = true
        documentName.maximumNumberOfLines = 2
        mainBox.moveCallback =  { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
            if !self.isSelect {
                if mouseEntered {
                    self.mainBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
                    self.mainBox.borderWidth = 0.0
                    self.documentName.textColor = NSColor.km_init(hex: "#252629")
                    self.mainBox.cornerRadius = 8.0
                } else {
                    self.mainBox.fillColor = .clear
                    self.mainBox.borderWidth = 0.0
                    self.documentName.textColor = NSColor.km_init(hex: "#252629")
                    self.mainBox.cornerRadius = 0.0
                }
            }
        }
    }
    
    func initializeUI() {
        
    }
    
    // MARK: private
    
    func refreshUI(_ path: URL) {
        filePathUrl = path
        
        if selectUrls.contains(path) {
            isSelect = true
            mainBox.fillColor = NSColor.km_init(hex: "#CED0D4", alpha: 0.6)
            mainBox.borderWidth = 1.0
            mainBox.borderColor = NSColor.km_init(hex: "#CED0D4")
            mainBox.cornerRadius = 8.0
        } else {
            isSelect = false
            mainBox.fillColor = .clear
            mainBox.borderWidth = 0.0
            mainBox.cornerRadius = 0.0
        }
        favoriteButton.isHidden = true
        imageBox.fillColor = .clear
        
        documentName.textColor = NSColor.km_init(hex: "#252629")
        
        documentName.stringValue = filePathUrl!.lastPathComponent
        mainBox.toolTip = filePathUrl!.lastPathComponent
        let image: NSImage = NSImage.previewForFile(path: filePathUrl!, ofSize: fileImageView.frame.size, asIcon: true) ?? NSImage()
        fileImageView.image = image
    }
    
    //MARK: update

    
    // MARK: Menu
    
    lazy var tableCellMenu: NSMenu = {
        let tableCellMenu = NSMenu()
        var item = NSMenuItem()
        item.title = NSLocalizedString("Show in Finder", comment: "")
        item.action = #selector(buttonItemClick_ShowPath)
        tableCellMenu.addItem(item)
        item = NSMenuItem()
        item.title = NSLocalizedString("Remove from Recents", comment: "")
        item.action = #selector(buttonItemClick_ClosePath)
        tableCellMenu.addItem(item)
        return tableCellMenu
    }()
    
    // MARK: Action
    
    @IBAction func buttonItemClick_ShowPath(sender: AnyObject) {
        if FileManager.default.fileExists(atPath: filePathUrl!.path) {
            NSWorkspace.shared.activateFileViewerSelecting([filePathUrl!])
        }
    }
    
    @IBAction func buttonItemClick_ClosePath(sender: AnyObject) {
        var selects: [URL] = []
        if selectUrls.count > 0 {
            for selecturl in self.selectUrls {
                selects.append(selecturl)
            }
        } else {
            selects.append(filePathUrl!)
        }
        if UserDefaults.standard.bool(forKey: "kHistoryDeleteNOReminderKey") {
            historyFileDeleteAction(selects)
        } else {
            let historyFileDeleteVC: KMHistoryFileDeleteWindowController = KMHistoryFileDeleteWindowController.init(windowNibName: NSNib.Name("KMHistoryFileDeleteWindowController"))
            historyFileDeleteVC.indexPaths = selects
            self.currentWindowController = historyFileDeleteVC
            historyFileDeleteVC.deleteCallback = { [weak self](indexPaths: [URL], windowController: KMHistoryFileDeleteWindowController) -> Void in
                if self != nil {
                    self?.currentWindowController = nil
                    self!.historyFileDeleteAction(indexPaths)
                }
            }
            self.view.window?.beginSheet(historyFileDeleteVC.window!)
        }
    }
    
    func historyFileDeleteAction(_ indexPaths: [URL]) -> Void {
        let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
        NSDocumentController.shared.clearRecentDocuments(nil)
        DispatchQueue.main.asyncAfter(deadline: .now()) { [self] in
            for (_, url) in urls.enumerated() {
                if !indexPaths.contains(url) {
                    NSDocumentController.shared.noteNewRecentDocumentURL(url)
                }
            }
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMHomeFileRectChange"), object: self.view.window)
        }
    }
    
    @IBAction func favoriteButtonAction(_ sender: NSButton) {
        KMPrint("收藏文件按钮")
    }
}