//
//  KMTableHeaderCell.swift
//  PDF Reader Pro
//
//  Created by kdanmobile on 2023/10/26.
//

import Cocoa

class KMTableHeaderCell: NSTableHeaderCell{
    override init(textCell string: String) {
        super.init(textCell: string)
        self.drawsBackground = false
    }
    
    required init(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
        super.draw(withFrame: cellFrame, in: controlView)
        cellFrame.fill()
        KMAppearance.Layout.l_2Color().set()
        self.drawInterior(withFrame: cellFrame, inView: controlView)
    }
    
    func drawInterior(withFrame cellFrame: NSRect, inView controlView: NSView) {
        var titleRect = self.titleRect(forBounds: cellFrame)
        titleRect.fill()
        KMAppearance.Layout.l_2Color().set()
        
        let layoutManager = NSLayoutManager()
        let lineHeight = layoutManager.defaultLineHeight(for: self.font!)
        titleRect.origin.y = (titleRect.size.height - lineHeight) / 2.0
        titleRect.size.height = lineHeight
        
        if self.alignment == NSTextAlignment.left {
            self.attributedStringValue.draw(with: titleRect, options: .usesLineFragmentOrigin)
        } else if self.alignment == NSTextAlignment.center {
            let width = self.widthOfString(self.title, withFont: self.font!)
            titleRect.origin.x += (titleRect.size.width - width) / 2.0
            titleRect.size.width = width
            self.attributedStringValue.draw(with: titleRect, options: .usesLineFragmentOrigin)
        } else {
            self.attributedStringValue.draw(with: titleRect, options: .usesLineFragmentOrigin)
        }
    }
    func drawSortIndicator(withFrame cellFrame: NSRect, inView controlView: NSView, ascending: Bool, priority: Int) { 
        
    }
    override func sortIndicatorRect(forBounds rect: NSRect) -> NSRect {
        return NSRect.zero
    }
    func widthOfString(_ string: String, withFont font: NSFont) -> CGFloat {
        let attributes = [NSAttributedString.Key.font: font]
        return NSAttributedString(string: string, attributes: attributes).size().width
    }
}