//
//  AutoTestAdvanceSettingView.swift
//  KdanAuto
//
//  Created by 朱东勇 on 2022/11/25.
//

import Foundation
import AppKit

let kItemCountPerRow   = 3

public protocol AutoTestAdvanceSettingViewDelegate : NSObjectProtocol {
    func advanceSettingDidUpdate(_ settingView:NSView?)
}


class AutoTestAdvanceSettingView : NSView, NSTableViewDataSource, NSTableViewDelegate, TestFileCellViewDelegate {
    
    @IBOutlet var _titleLbl : NSTextField!
    @IBOutlet var _keyScrollView : NSScrollView!
    @IBOutlet var _keyContentView : NSView!
    
    @IBOutlet var _fileList : NSTableView!
    @IBOutlet var _replaceAllBtn : NSButton!
    
    @IBOutlet var _addBtn : NSButton!
    
    var _keyViews : NSMutableArray!
    var _autoTestObj : AutoTest?
    
    var _files : [String]! = []
    
    var _appleInterface : Any?
    
    var delegate : AutoTestAdvanceSettingViewDelegate?
    
    override func awakeFromNib() {
        self.wantsLayer = true;
        
        updateBGColor()
        
        _addBtn.isHidden = true;
        
        _appleInterface = DistributedNotificationCenter.default().addObserver(forName: Notification.Name("AppleInterfaceThemeChangedNotification"), object: nil, queue: nil) { notification in
            DispatchQueue.main.async {
                self.updateBGColor()
            }
        }
    }
    
    func isDarkMode() -> Bool {
        let apperace = NSApplication.shared.effectiveAppearance
        
        return apperace.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
    }
    
    func updateBGColor() {
        self.wantsLayer = true;
        if (isDarkMode()) {
            self.layer?.backgroundColor = NSColor(white: 0.196, alpha: 1).cgColor
        }else {
            self.layer?.backgroundColor = NSColor(white: 0.925, alpha: 1).cgColor
        }
//        self.layer?.backgroundColor = NSColor(named: "AdvanceBackgrougColor")?.cgColor
    }
    
    // Setter
    let kCheckBtnDefaultHeight = 25.0
    public func setAutoTestObj(_ obj:AutoTest?) {
        _autoTestObj = obj;
        
        // Set Title
//        self.setAccessibilityEnabled((_autoTestObj?.isOriginFileExist() == true && _autoTestObj?.isCheckFileExist() == true))
//
        
        _addBtn.isHidden = nil == _autoTestObj;
        if nil != _autoTestObj {
            _titleLbl.stringValue = String("[\(_autoTestObj?.fileType() as! String)]\(_autoTestObj?.name() as! String)")
            let checkKeys = _autoTestObj?.keys() as! NSArray
            let selectKeys = _autoTestObj?.selectedKeys() as! NSArray
            
            if _keyViews == nil {
                _keyViews = NSMutableArray()
            }
            while (_keyViews.count != checkKeys.count) {
                if (_keyViews.count > checkKeys.count) {
                    (_keyViews.lastObject as! NSButton).removeFromSuperview()
                    _keyViews.removeLastObject()
                }else {
                    let checkBtn = NSButton(checkboxWithTitle: "", target: self, action: #selector(keyChecked))
                    
                    _keyContentView.addSubview(checkBtn);
                    _keyViews.add(checkBtn)
                }
            }
            
            var height = CGFloat((_keyViews.count + 1)/kItemCountPerRow * (Int(kCheckBtnDefaultHeight) + 5));
        
            //        _keyContentView.frame = NSRect(x: 0, y: 0, width: width, height: kTFDefaultHeight)
            if (height > _keyScrollView.frame.height) {
                _keyContentView.setFrameSize(NSSize.init(width: _keyScrollView.frame.width - 28, height: height))
            }else {
                height = _keyScrollView.frame.height - 20
                _keyContentView.setFrameSize(NSSize.init(width: _keyScrollView.frame.width - 28, height: _keyScrollView.frame.height))
            }
            
            for btn in _keyViews {
                let i = _keyViews.index(of: btn)
                let checkBtn = btn as! NSButton
                
                checkBtn.title = checkKeys[i] as! String;
                
                // Update Check Status
                if selectKeys.contains(checkKeys[i]) {
                    checkBtn.state = .on
                }else {
                    checkBtn.state = .off
                }
                
                checkBtn.sizeToFit()
                
                checkBtn.frame = CGRect.init(x: CGFloat(i % kItemCountPerRow) * _keyContentView.frame.size.width/CGFloat(kItemCountPerRow), y: CGFloat(height - kCheckBtnDefaultHeight), width: checkBtn.frame.width, height: kCheckBtnDefaultHeight)
                checkBtn.autoresizingMask = .maxXMargin.union(.minYMargin)
                
                if i % kItemCountPerRow == (kItemCountPerRow - 1) {
                    height = height - checkBtn.frame.height - 5
                }
            }
            
            _keyScrollView.documentView = _keyContentView;
            
            _files = DataModel.shared.originFilesFor(String(_autoTestObj?.fileType() ?? ""),
                                                     type: String(_autoTestObj?.type() ?? ""))
            _fileList.reloadData()
            
            _replaceAllBtn.isEnabled = _autoTestObj!.canUpdateRefImage()
        }else {
            _titleLbl.stringValue = ""
            if _keyViews == nil {
                _keyViews = NSMutableArray()
            }
            while (_keyViews.count != 0) {
                (_keyViews.lastObject as! NSView).removeFromSuperview()
                _keyViews.removeLastObject()
            }
            
            _files = []
            _fileList.reloadData()
            _replaceAllBtn.isEnabled = false
        }
    }
    
    
    /// IBActionn
    @IBAction func keyChecked(_ sender:NSButton) {
        var currentSelectedKeys = NSMutableArray()
        
        let checkKeys = _autoTestObj?.keys() as! NSArray
        
        for btn in _keyViews {
            let cBtn = btn as! NSButton
            
            if cBtn.state == .on {
                let index = _keyViews.index(of: btn)
                
                currentSelectedKeys.add(checkKeys[index])
            }
        }
        
        _autoTestObj?.setSelectedKeys(currentSelectedKeys)
        
        if delegate != nil {
            delegate?.advanceSettingDidUpdate(self)
        }
    }
    
    @IBAction func replaceAllAction(_ sender:NSButton) {
        if nil != _autoTestObj {
            _autoTestObj?.updateRefImage()
        }
    }
    
    @IBAction func addFileAction(_ sender:NSButton) {
        if nil == _autoTestObj {
            return
        }
        
        let originDirectory = _autoTestObj?.originFileDirectory()
        
        let openPanel = NSOpenPanel()
        
        openPanel.canChooseFiles = true
        openPanel.allowedContentTypes = [.pdf]
        openPanel.canChooseDirectories = false
        
        let comboBox = NSComboBox.init(frame: NSRect.init(x: 0, y: 0, width: 100, height: 25))
        comboBox.removeAllItems()
        comboBox.addItems(withObjectValues: ["添加超链接", "导入文件"])
        comboBox.selectItem(at: 0)
        openPanel.accessoryView = comboBox;
        
        if openPanel.runModal() == NSApplication.ModalResponse.OK {
            let path = openPanel.url?.relativePath
            
            let resultPath = NSString(string: originDirectory!).appendingPathComponent(openPanel.url!.lastPathComponent)
            
            if FileManager.default.fileExists(atPath: path!) {
                if comboBox.indexOfSelectedItem == 0 {
                    try! FileManager.default.createSymbolicLink(atPath: resultPath, withDestinationPath: path!)
                }else {
                    try! FileManager.default.copyItem(atPath: path!, toPath: resultPath)
                }
                
                _files = DataModel.shared.originFilesFor(String(_autoTestObj?.fileType() ?? ""),
                                                         type: String(_autoTestObj?.type() ?? ""))
                _fileList.reloadData()
            }
        }
    }
    
    
    // TableView Delegate
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        let cellView = TestFileCellView.shared()
        
        if (_files.count >= row) {
            let title = _files[row]
            
            cellView?.setTitle(title)
            cellView?._delegate = self
            
            if _autoTestObj != nil {
                cellView?.setNeedReplaceBtn(_autoTestObj!.canUpdateRefImage(title))
            }else {
                cellView?.setNeedReplaceBtn(false)
            }
            
            if _autoTestObj != nil && _autoTestObj?.status() == .Finished {
                cellView?.setNeedDegreeBtn(true)
                cellView?.setDegree((_autoTestObj?.degreeOfFile(title))!)
            }else {
                cellView?.setNeedDegreeBtn(false)
            }
        }
        
        return cellView
    }
    
    func selectionShouldChange(in tableView: NSTableView) -> Bool {
        
        return true
    }
    
    func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
        
        return false
    }
    
    func tableView(_ tableView: NSTableView, shouldSelect tableColumn: NSTableColumn?) -> Bool {
        
        return false
    }
    
    func tableView(_ tableView: NSTableView, mouseDownInHeaderOf tableColumn: NSTableColumn) {
        
    }
    
    func tableView(_ tableView: NSTableView, didClick tableColumn: NSTableColumn) {
        
    }
    
    func tableView(_ tableView: NSTableView, didDrag tableColumn: NSTableColumn) {
        
    }
    
    func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
        return 30
    }
    
    func tableView(_ tableView: NSTableView, isGroupRow row: Int) -> Bool {
        return false
    }
    
    func tableView(_ tableView: NSTableView, sizeToFitWidthOfColumn column: Int) -> CGFloat {
        return tableView.frame.width
    }
    
    func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] {
        return []
    }
    
    func tableViewSelectionDidChange(_ notification: Notification) {
        
    }
    
    // TableView Data Source
    func numberOfRows(in tableView: NSTableView) -> Int {
        return _files.count
    }
    
    // TestFileCellViewDelegate
    func fileCellNeedReplace(_ cell: TestFileCellView, fileName: String) {
        if (_autoTestObj != nil) {
            _autoTestObj?.updateRefImage(fileName)
        }
        _fileList.reloadData()
    }
    
    func fileCellNeedShowReport(_ cell: TestFileCellView, fileName: String) {
        
    }
}
