//
//  KMOCToolClass.swift
//  Cisdem PDFMaster
//
//  Created by lizhe on 2023/9/26.
//

import Cocoa

struct MwcFlags {
    var caseInsensitiveSearch: Int = 1
    var wholeWordSearch: Int = 1
    var settingUpWindow: Int = 1
    // 正在切换全屏的标识
    var isSwitchingFullScreen: Int = 0
    var wantsPresentation: Int = 1
}

@objc enum SKInteractionMode: Int {
    case SKNormalMode = 0 // 常规模式
    case SKFullScreenMode
    case SKPresentationMode // 幻灯片模式
    case SKLegacyFullScreenMode
}

class KMOCToolClass {
    class func filterAnnotation(annotations: [Any], types: [Any]) -> [Any] {
        let array = annotations
        let leftExpression = NSExpression(forKeyPath: "type")
        let rightExpression = NSExpression(forConstantValue: types)
        let predicate = NSComparisonPredicate(
            leftExpression: leftExpression,
            rightExpression: rightExpression,
            modifier: .direct,
            type: .in,
            options: .diacriticInsensitive
        )
        return (array as NSArray).filtered(using: predicate)
    }
    
    class func filterAnnotation(annotations: [Any], colors: [Any]) -> [Any] {
        var array = annotations
        if array.contains(where: { $0 is NSColor && ($0 as! NSColor) == NSColor.clear }) {
            array.removeAll { $0 is NSColor && ($0 as! NSColor) == NSColor.clear }
        }
        let leftExpression = NSExpression(forKeyPath: "color")
        let rightExpression = NSExpression(forConstantValue: colors)
        let predicate = NSComparisonPredicate(
            leftExpression: leftExpression,
            rightExpression: rightExpression,
            modifier: .direct,
            type: .in,
            options: .diacriticInsensitive
        )
        return (array as NSArray).filtered(using: predicate)
    }
    
    class func filterAnnotation(annotations: [Any], authors: [Any]) -> [Any] {
        let array = annotations
        let leftExpression = NSExpression(forKeyPath: "userName")
        let rightExpression = NSExpression(forConstantValue: authors)
        let predicate = NSComparisonPredicate(
            leftExpression: leftExpression,
            rightExpression: rightExpression,
            modifier: .direct,
            type: .in,
            options: .diacriticInsensitive
        )
        return (array as NSArray).filtered(using: predicate)
    }
    
    class func arrayContains(array: [Any]?, annotation item: Any?) -> Bool {
        return array?.contains { $0 as AnyObject === item as AnyObject } ?? false
    }
    
    class func arrayIndexOf<T: Equatable>(array: [T], item: T) -> Int? {
        guard let index = array.firstIndex(of: item) else {
            return nil // Return nil to indicate that the item was not found
        }
        return index
    }
    
    class func exproString(annotation: CPDFAnnotation) -> String {
        var exproString = ""
        
        if let markupAnnotation = annotation as? CPDFMarkupAnnotation,
           let page = markupAnnotation.page,
           let points = markupAnnotation.quadrilateralPoints as? [CGPoint], // Cast to [CGPoint]
           points.count % 4 == 0 {
            
            for i in stride(from: 0, to: points.count, by: 4) {
                let ptlt = points[i]
                let ptrt = points[i + 1]
                let ptlb = points[i + 2]
                let ptrb = points[i + 3]
                let rect = CGRect(x: ptlt.x, y: ptlt.y, width: ptrt.x - ptlt.x, height: ptrt.y - ptlt.y)
                
                if let string = page.string(for: rect), !string.isEmpty {
                    if !exproString.isEmpty {
                        exproString += "\n"
                    }
                    exproString += string
                }
            }
        }
        
        return exproString
    }
    
    class func getAttributedString(selection: CPDFSelection, keyword: String) -> NSMutableAttributedString {
        guard let currentPage = selection.page else {
            return NSMutableAttributedString()
        }
        
        let range = selection.range
        var startLocation = 0
        let maxLocation: UInt = 10
        let maxEndLocation: UInt = 50

        var keyLocation = 0
        
        if range.location > maxLocation {
            startLocation = range.location - Int(maxLocation)
            keyLocation = Int(maxLocation)
        } else {
            startLocation = 0
            keyLocation = range.location
        }
        
        var endLocation: UInt = 0
        
        if range.location + Int(maxEndLocation) > currentPage.numberOfCharacters {
            endLocation = UInt(currentPage.numberOfCharacters)
        } else {
            endLocation = UInt(range.location + Int(maxEndLocation))
        }
        
        var attributed: NSMutableAttributedString = NSMutableAttributedString()
        
        if endLocation > UInt(startLocation) {
            var string = currentPage.string(for: NSRange(location: startLocation, length: Int(endLocation) - startLocation))
            var currentString = "..."
            
//            let stringArr = string?.components(separatedBy: CharacterSet.newlines) ?? []
//            
//            for s in stringArr {
//                if s.isEmpty {
//                    currentString += "  "
//                } else {
//                    currentString += s
//                }
//            }
            
            string = string?.replacingOccurrences(of: "\r\n", with: "  ")
            string = string?.replacingOccurrences(of: "\r", with: " ")
            string = string?.replacingOccurrences(of: "\n", with: " ")
            string = string?.replacingOccurrences(of: "\n", with: " ")
            string = string?.replacingOccurrences(of: "\u{2028}", with: " ")
            string = string?.replacingOccurrences(of: "\u{2029}", with: " ")
            currentString += string ?? ""

            let tRange = NSRange(location: keyLocation + 3, length: keyword.count)
            
            if tRange.location != NSNotFound {
                attributed = NSMutableAttributedString(string: currentString)
                
                let paragraphStyle = NSMutableParagraphStyle()
                paragraphStyle.firstLineHeadIndent = 10.0
                paragraphStyle.headIndent = 10.0
                paragraphStyle.lineBreakMode = .byCharWrapping
                paragraphStyle.lineHeightMultiple = 1.32
                
                let dic: [NSAttributedString.Key: Any] = [
                    .font: NSFont(name: "SFProText-Regular", size: 14.0)!,
//                    .foregroundColor: NSColor(red: 0.145, green: 0.149, blue: 0.161, alpha: 1),
                    .paragraphStyle: paragraphStyle
                ]
                
                let fullRange = NSRange(location: 0, length: attributed.length)
                attributed.setAttributes(dic, range: fullRange)
                
                // Highlight string
                let highlightDic: [NSAttributedString.Key: Any] = [
                    .backgroundColor: KMAppearance.KM_FFF700_Color60()
                ]
                
                if attributed.length > tRange.length + tRange.location {
                    attributed.addAttributes(highlightDic, range: tRange)
                }
            }
        }
        
        return attributed
    }
}