//
//  KMPageEditThumbnailItem.swift
//  PDF Master
//
//  Created by tangchao on 2023/1/6.
//

import Cocoa

class KMPageEditThumbnailItem: NSCollectionViewItem {
    private let _textBoxSpace: CGFloat = 2
    private let _textLabelHeight: CGFloat = 15
    
    internal var backgroundView = NSView()
    
    internal lazy var pageBox : NSView = {
        let pageBox = NSView()
        pageBox.wantsLayer = true
        return pageBox
    }()
    
    internal lazy var textBox : NSView = {
        let textBox = NSView()
        
        return textBox
    }()
    
    internal lazy var pageTextLabel : NSTextField = {
        let label = NSTextField()
        label.isEditable = false
        label.isBordered = false
        label.isSelectable = false
        label.drawsBackground = false
        return label
    }()
    
    internal lazy var pageSizeTextLabel : NSTextField = {
        let label = NSTextField()
        label.isEditable = false
        label.isBordered = false
        label.drawsBackground = false
        return label
    }()
    
    internal lazy var pageView = KMPDFThumbnialPageView()
    
    internal var page : CPDFPage = CPDFPage()
    var isShowPageSize: Bool = false
    
    var doubleClickAction: KMCommonBlock?
    var mouseDownAction: KMCommonBlock?
    var rightMouseDownAction: KMCommonBlock?
    
    override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.addSubview(self.backgroundView)
        
        self.view.addSubview(self.pageBox)
        self.pageBox.addSubview(self.pageView)
        self.view.addSubview(self.textBox)
        self.textBox.addSubview(self.pageTextLabel)
        self.textBox.addSubview(self.pageSizeTextLabel)
        
        self.backgroundView.wantsLayer = true
        self.backgroundView.layer?.cornerRadius = 8.0
        self.backgroundView.layer?.masksToBounds = true
        self.backgroundView.layer?.borderWidth = 1.0
        self.isSelected = false
        
        self.pageView.wantsLayer = true
        self.pageView.layer?.borderWidth = 1
        self.pageView.layer?.borderColor = NSColor(hex: "#0000001A").cgColor
        self.pageView.layer?.cornerRadius = 4
        self.pageView.layer?.masksToBounds = true
        
        self.pageTextLabel.font = NSFont.SFProTextRegular(14)
        self.pageTextLabel.textColor = NSColor.titleColor()
        self.pageSizeTextLabel.font = NSFont.SFProTextRegular(14)
        self.pageSizeTextLabel.textColor = NSColor(hex: "#616469")
    }
    
    override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)
        
        if (event.clickCount > 1) {
            guard let callback = self.doubleClickAction else {
                return
            }
            
            callback()
        } else {
            if (event.modifierFlags.contains(.command) || event.modifierFlags.contains(.shift)) {
                return
            }
            if (self.isSelected == false) {
                return
            }
            
            guard let callback = self.mouseDownAction else {
                return
            }
            callback()
        }
    }
    
    override func rightMouseDown(with event: NSEvent) {
        if (self.isSelected == true) {
            super.rightMouseDown(with: event)
            return
        }
        
        guard let callback = self.rightMouseDownAction else {
            super.rightMouseDown(with: event)
            return
        }
        callback()
        super.rightMouseDown(with: event)
    }
     
    override var isSelected: Bool {
         get {
             return super.isSelected
         }
         set {
             super.isSelected = newValue
             
             if (newValue) {
                 self.backgroundView.layer?.backgroundColor = NSColor(hex: "#1770F41A").cgColor
                 self.backgroundView.layer?.borderColor = NSColor(hex: "#1770F4").cgColor
             } else {
                 self.backgroundView.layer?.backgroundColor = NSColor.clear.cgColor
                 self.backgroundView.layer?.borderColor = NSColor.clear.cgColor
             }
         }
     }
     
     func setPage(page:CPDFPage!) {
         self.page = page
         self.pageView.page = page
         let index = page.document.index(for: page) + 1
         self.pageTextLabel.stringValue = "\(index)"
         
         let rect = self.page.bounds(for: .cropBox)
         let width = KMPageSizeTool.conversion(withUnit: "mm", value: rect.width/595*210)
         let height = KMPageSizeTool.conversion(withUnit: "mm", value: rect.height/842*297)
         
         if (page.rotation == 90 || page.rotation == 270 || page.rotation == -90 || page.rotation == -270) {
             self.pageSizeTextLabel.stringValue = String(format: "%.f * %.f \(NSLocalizedString("mm", comment: ""))", height.stringToCGFloat(), width.stringToCGFloat())
         } else {
             self.pageSizeTextLabel.stringValue = String(format: "%.f * %.f \(NSLocalizedString("mm", comment: ""))", width.stringToCGFloat(), height.stringToCGFloat())
         }
         
         self.updateFrame()
     }
         
     func updateFrame () {
         let viewWidth: CGFloat = NSWidth(self.view.bounds)
         let viewHeight: CGFloat = NSHeight(self.view.bounds)
         
         let backgroundViewX: CGFloat = 12;
         let backgroundViewY: CGFloat = 24;
         let backgroundViewW: CGFloat = viewWidth - backgroundViewX * 2;
         let backgroundViewH: CGFloat = viewHeight - 24;
         self.backgroundView.frame = NSMakeRect(backgroundViewX, backgroundViewY, backgroundViewW, backgroundViewH)
         
         var bounds = self.page.bounds
         let transform = self.page.transform()
         bounds = bounds.applying(transform)
         
         var size = NSMakeSize(backgroundViewW-32, backgroundViewH-46)
         if (self.isShowPageSize == false) {
            size = NSMakeSize(backgroundViewW-32, backgroundViewH-72)
         }

         if (page.rotation == -90 || page.rotation == -270) {
             let height = bounds.size.height
             bounds.size.height = bounds.size.width
             bounds.size.width = height
         }
         
         if (page.rotation == -90 || page.rotation == -270) {
             let height = size.height
             size.height = size.width
             size.width = height
         }
         
         if bounds.size.width > bounds.size.height {
             if (bounds.size.width > 0) {
                 size.height = size.width * bounds.size.height / bounds.size.width
             }
         } else {
             if (bounds.size.height > 0) {
                 size.width = size.height * bounds.size.width / bounds.size.height
             }
         }
         
         let height = _textLabelHeight
         let labelBoxY: CGFloat = _textBoxSpace + NSMinY(self.backgroundView.frame)+6
         let labelSize = NSMakeSize(size.width, CGFloat(MAXFLOAT))
         let textSize = self.pageTextLabel.sizeThatFits(labelSize)
         if self.isShowPageSize == false {
             self.pageSizeTextLabel.sizeToFit()
             let pageSizeLabelSize = self.pageSizeTextLabel.frame.size
             let width = max(textSize.width, pageSizeLabelSize.width) + 5
             
             self.pageSizeTextLabel.isHidden = false
             self.pageSizeTextLabel.frame = NSMakeRect((width-pageSizeLabelSize.width)*0.5, 4, pageSizeLabelSize.width, 22);
             self.pageTextLabel.frame = NSMakeRect((width-textSize.width)*0.5, self.pageSizeTextLabel.frame.maxY+8, textSize.width, height);
             let boxH: CGFloat = 48
             
             self.textBox.frame = NSMakeRect((viewWidth - width)*0.5, labelBoxY, width, boxH)
         } else {
             self.pageSizeTextLabel.isHidden = true
             
             let textWidth = textSize.width + 5
             let boxH: CGFloat = 22
             self.textBox.frame = NSMakeRect((viewWidth-textWidth)*0.5, labelBoxY, textWidth, boxH)
             
             self.pageTextLabel.frame = NSMakeRect((textWidth-textSize.width)*0.5, 4, textSize.width, height);
         }
         
         let margin: CGFloat = 16 + NSMinX(self.backgroundView.frame)
         let pageBoxY: CGFloat = self.textBox.frame.maxY+8
         let pageBoxW: CGFloat = viewWidth-margin*2
         let pageBoxH: CGFloat = viewHeight-pageBoxY-8
         self.pageBox.frame = NSMakeRect(margin, pageBoxY, pageBoxW, pageBoxH)
         
         var pageX: CGFloat = (NSWidth(self.pageBox.frame)-size.width)*0.5
         if (pageX < 0) {
             let tempWidth = size.width + pageX * 2
             let scale = tempWidth / size.width
             size.width = size.width * scale
             size.height = size.height * scale
             
             pageX = 0
         }
         let pageY: CGFloat = (NSHeight(self.pageBox.frame)-size.height)*0.5
         self.pageView.frame = NSMakeRect(pageX, pageY, size.width, size.height)
     }
}