//
//  KMBatchWindowController.swift
//  PDF Master
//
//  Created by lizhe on 2023/1/12.
//

import Cocoa
import KMComponentLibrary

class CustomWindowController: NSWindowController {
    override func windowDidLoad() {
        super.windowDidLoad()
        
        // 创建一个工具栏
        let toolbar = NSToolbar(identifier: "CustomToolbar")
        toolbar.delegate = self
        toolbar.allowsUserCustomization = false
        toolbar.displayMode = .iconAndLabel

        // 设置窗口的工具栏
        self.window?.toolbar = toolbar
    }
}

extension CustomWindowController: NSToolbarDelegate {
    func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
        let item = NSToolbarItem(itemIdentifier: itemIdentifier)
        item.label = "Action"
        item.target = self
        item.action = #selector(toolbarAction)
        return item
    }

    func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
        return [.flexibleSpace, NSToolbarItem.Identifier("CustomItem")]
    }

    @objc func toolbarAction() {
        print("Toolbar action triggered!")
    }
}

class KMBatchWindowController: NSWindowController {

    @IBOutlet weak var batchPrecessingView: KMBatchProcessingView!
    @IBOutlet weak var batchCollectionView: KMBatchCollectionView!
    @IBOutlet weak var batchCollectionViewWidthConstraint: NSLayoutConstraint!
    @IBOutlet weak var batchHandleView: NSView!
    @IBOutlet weak var settingView: KMBatchSettingView!
    @IBOutlet weak var processView: NSView!
    
    var isDisable: Bool = false {
        didSet {
            self.batchCollectionView.isDisable = isDisable
            self.settingView.isDisable = isDisable
        }
    }

    private var batchData: [KMBatchProcessingTableViewModel]?
    
    @objc var inputData:[URL] = [] {
        didSet {
            self.reloadData()
        }
    }
    
    @objc var inputDataModel:[KMBatchProcessingTableViewModel] = [] {
        didSet {
            self.reloadData()
        }
    }
    
    var inputFileModels:[KMBatchProcessingTableViewModel] = [] {
        didSet {
            self.reloadData()
        }
    }
    
    var inputSubType: Any? {
        didSet {
            self.reloadData()
        }
    }
    
    var type: KMBatchCollectionViewType = .convertPDF {
        didSet {
            if type == .imageToPDF {
                var rect = self.window!.frame
                rect.size.width = 880
                rect.size.height = 600
                
                self.window?.setFrame(rect, display: true, animate: false)
                self.window?.minSize = CGSize(width: 880, height: 600)
            }
            
            self.reloadData()
        }
    }
    
    deinit {
        KMPrint("KMImageToPDFWindowController 释放")
        NotificationCenter.default.removeObserver(self)
    }
    
    override func windowDidLoad() {
        super.windowDidLoad()

        guard let window = self.window else { return }
                
        // 隐藏标题栏
        window.titleVisibility = .hidden
        window.titlebarAppearsTransparent = true
        
//        // 添加自定义导航栏
//        let navBar = NSView(frame: NSRect(x: 0, y: window.frame.height - 10, width: window.frame.width, height: 10))
//        navBar.wantsLayer = true
//        navBar.layer?.backgroundColor = ComponentLibrary.shared.backgroundColor(forToken: "colorBg/layout-middle")?.cgColor // 自定义颜色
//        
//        // 添加到窗口内容视图中
//        window.contentView?.addSubview(navBar)
//        
//        // 添加约束
//        navBar.translatesAutoresizingMaskIntoConstraints = false
//        NSLayoutConstraint.activate([
//            navBar.topAnchor.constraint(equalTo: window.contentView!.topAnchor),
//            navBar.leadingAnchor.constraint(equalTo: window.contentView!.leadingAnchor),
//            navBar.trailingAnchor.constraint(equalTo: window.contentView!.trailingAnchor),
//            navBar.heightAnchor.constraint(equalToConstant: 10)
//        ])

        self.setup()
        self.reloadData()
        self.addNotification()
    }
    
    func addNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(bacthProcessingNotification), name: NSNotification.Name(kBacthProcessNotification), object: nil)
    }
    
    func setup() {
        self.window?.contentView?.wantsLayer = true
        self.window?.contentView?.layer?.backgroundColor = ComponentLibrary.shared.backgroundColor(forToken: "colorBg/layout-middle")?.cgColor
        // 修改窗口背景颜色
        self.window?.backgroundColor = ComponentLibrary.shared.backgroundColor(forToken: "colorBg/layout-middle")
        
//        self.window?.contentView?.border(ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider") , 0.5, 0)
        
//        self.processView.wantsLayer = true
//        self.processView.border(ComponentLibrary.shared.getComponentColorFromKey("colorBorder/divider"), 0.5)
        
        self.batchCollectionView.delegate = self
        self.batchPrecessingView.delegate = self
        
        self.settingView.type = .convertPDF
    }
    
    func reloadData() {
        if self.type == .imageToPDF {
            batchCollectionViewWidthConstraint.constant = 0
        } else {
            batchCollectionViewWidthConstraint.constant = 240
        }
        
        self.batchPrecessingView.inputType = self.type
        self.batchCollectionView.inputType = self.type
        self.settingView.type = self.type
        self.settingView.subType = self.inputSubType
        
        if inputData.count != 0 {
            self.batchPrecessingView.inputData = inputData
        }
        if inputDataModel.count != 0 {
            self.batchPrecessingView.inputDataModel = inputDataModel
        }
    }
    
    //MARK: 打开文件
    static func openFiles(window: NSWindow) {
        if KMBatchWindowController.isSampleController() {
            KMPrint("存在相同文件")
            if let controller: KMBatchWindowController = self.fetchSampleController() {
                controller.showWindow(window)
            }
        } else {
            KMBatchProcessingView.openfiles(window: window) { openPanel in
                openPanel.title = "选择图片"
                openPanel.canChooseDirectories = false
                openPanel.canChooseFiles = true
                openPanel.allowsMultipleSelection = true
                openPanel.allowedFileTypes = KMOCRModel.supportedTypes()
            } completion: { (panel ,data) in
                if data.count != 0 {
                    let batchWindowController: KMBatchWindowController = KMBatchWindowController.init(windowNibName: "KMBatchWindowController")
                    batchWindowController.showWindow(window)
                    batchWindowController.batchPrecessingView.inputData = data
                }
            }
        }
    }
    
    //MARK: 打开文件
    static func openFile(_ url: URL?, _ type: KMBatchCollectionViewType, _ subType: Any = "") {
        if KMBatchWindowController.isSampleController() {
            if let controller: KMBatchWindowController = self.fetchSampleController() {
                KMPrint("存在相同文件")
                controller.inputSubType = subType
                controller.type = type
                controller.showWindow(NSApp.mainWindow)
            }
        } else {
            let batchWindowController: KMBatchWindowController = KMBatchWindowController.init(windowNibName: "KMBatchWindowController")
            batchWindowController.showWindow(NSApp.mainWindow)
            if url != nil {
                batchWindowController.batchPrecessingView.inputData = [url!]
            }
            
            batchWindowController.inputSubType = subType
            batchWindowController.type = type
        }
    }
    
    static func isSampleController() -> Bool {
        for window in NSApp.windows {
            let controller = window.windowController
            if controller is KMBatchWindowController {
                return true
            }
        }
        return false
    }
    
    static func fetchSampleController() -> KMBatchWindowController? {
        for window in NSApp.windows {
            let controller = window.windowController
            if controller is KMBatchWindowController {
                return controller as? KMBatchWindowController
            }
        }
        
        return nil
    }
}

extension KMBatchWindowController: KMBatchProcessingViewDelegate {
    func reloadData(data: [KMBatchProcessingTableViewModel]) {
        self.batchData = data
        
        KMBatchManager.manager.filesData = data
        self.settingView.filesData = data
    }
}

extension KMBatchWindowController: KMBatchCollectionViewDelegate {
    func didSelect(index: IndexPath, data: KMBatchCollectionViewModel) {
        KMPrint(data.type.rawValue)
        let dataType: KMBatchCollectionViewType = data.type
        self.settingView.type = dataType
        self.batchPrecessingView.inputType = dataType
    }
}

extension KMBatchWindowController {
    @objc func bacthProcessingNotification() {
        if KMBatchManager.manager.state == .processing {
            self.isDisable = true
        } else {
            self.isDisable = false
        }
    }
}