//
//  KMPopMenuButtonCell.swift
//  PDF Reader Pro
//
//  Created by wanjun on 2023/10/7.
//

import Cocoa

class KMPopMenuButtonCell: NSButtonCell {

    override func titleRect(forBounds rect: NSRect) -> NSRect {
        var rect1 = super.titleRect(forBounds: rect)
        if ((self.image?.size.width) != nil) {
            return CGRectMake(21 + 5 + (self.image?.size.width)!, rect1.origin.y, self.attributedTitle.size().width, self.attributedTitle.size().height)
        } else {
            return CGRectMake(21 + 5, rect1.origin.y, self.attributedTitle.size().width, self.attributedTitle.size().height)
        }
    }
    
    override func drawTitle(_ title: NSAttributedString, withFrame frame: NSRect, in controlView: NSView) -> NSRect {
        if !isEnabled {
            var txtColor = NSColor(red: 0, green: 0, blue: 0, alpha: 0.8)
            
            if #available(macOS 10.14, *) {
                if let appearanceName = NSApp.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) {
                    if appearanceName == .darkAqua {
                        txtColor = NSColor(white: 1.0, alpha: 0.5)
                        let myAttr = NSMutableAttributedString(attributedString: title)
                        myAttr.addAttribute(.foregroundColor, value: txtColor, range: NSRange(location: 0, length: myAttr.length))
                        return super.drawTitle(myAttr, withFrame: frame, in: controlView)
                    }
                }
            }
        }
        return super.drawTitle(title, withFrame: frame, in: controlView)
    }
    
    override func imageRect(forBounds rect: NSRect) -> NSRect {
        if let image = self.image {
            var imageRect = super.imageRect(forBounds: rect)
            imageRect.origin.x = 21
            return imageRect
        }
        return NSRect.zero
    }
}