//
//  KMHomeDragView.swift
//  PDF Master
//
//  Created by wanjun on 2022/11/24.
//

import Cocoa

protocol KMHomeDragViewDelegate: NSObjectProtocol {
    func homeDragView(_ viewController: KMHomeDragView, filePath: URL)
    func homeDragView(_ viewController: KMHomeDragView, notSupport: Bool)
}

class KMHomeDragView: NSView {
    
    @IBOutlet weak var dragView: NSView!
    @IBOutlet weak var dragLabel: NSTextField!
    @IBOutlet weak var dragViewHeight: NSLayoutConstraint!

    open weak var delete: KMHomeDragViewDelegate?

    var isDraggingEntered = false
    
    // MARK: Init
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        initializeUI()
        
        dragView.isHidden = true
        
        self.registerForDraggedTypes([NSPasteboard.PasteboardType.fileURL])
    }
    
    func initializeUI() -> Void {
        self.wantsLayer = true;
        self.layer?.borderColor = .clear
        let typography = KMDesignToken.shared.typography(withToken: "notification.toast.mac-text")
        dragLabel.textColor = KMDesignToken.shared.fill(withToken: "notification.toast.mac-text")
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = typography.lineHeight.stringToCGFloat()
        dragLabel.attributedStringValue = NSAttributedString(string: NSLocalizedString("Drop to open it", comment: ""), attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])

        var fontFamily: String = typography.fontFamily
        let fontWeight: String = typography.fontWeight
        if fontFamily.contains(" ") {
            fontFamily = fontFamily.replacingOccurrences(of: " ", with: "")
        }
        if fontWeight != "" {
            fontFamily = String(format: "%@-%@", fontFamily, fontWeight)
        }
        dragLabel.font = NSFont(name: fontFamily, size: typography.fontSize.stringToCGFloat()) ?? NSFont.systemFont(ofSize: typography.fontSize.stringToCGFloat())

        dragViewHeight.constant = KMDesignToken.shared.height(withToken: "notification.toast.bg").stringToCGFloat()
    }
    
    // MARK: private

    func dragEntered(_ isDragEntered: Bool) -> Void {
        if isDragEntered {
            self.layer?.backgroundColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1).cgColor
            self.layer?.cornerRadius = 16.0
            dragView.wantsLayer = true
            dragView.layer?.backgroundColor = KMDesignToken.shared.fill(withToken: "notification.toast.bg").cgColor
            dragView.layer?.cornerRadius = KMDesignToken.shared.borderRadius(withToken: "notification.toast.bg").stringToCGFloat()
            let boxShadow = KMDesignToken.shared.boxShadow(withToken: "notification.toast.bg") as KMBoxShadowValue
//            let shadow = NSShadow()
//            shadow.shadowColor = boxShadow.color
//            shadow.shadowOffset = CGSizeMake(boxShadow.x.stringToCGFloat(), boxShadow.y.stringToCGFloat())
//            shadow.shadowBlurRadius = (boxShadow.blur.stringToCGFloat())
//            dragView.shadow = shadow
            
            dragView.isHidden = false
            isDraggingEntered = true
            self.needsDisplay = true
        } else {
            self.layer?.borderColor = .clear
            self.layer?.backgroundColor = .clear
            
            dragView.isHidden = true
            isDraggingEntered = false
            self.needsDisplay = true
        }
    }
    
    // MARK: Drag
    
    override func draggingExited(_ sender: NSDraggingInfo?) {
        dragEntered(false)
    }
    
    override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
        let pboard = sender.draggingPasteboard
        if (pboard.pasteboardItems == nil) {
            return []
        }
        
        var canAdd = true
        for item in pboard.pasteboardItems! {
            let fileURL = item.string(forType: .fileURL)
            if (fileURL == nil) {
                canAdd = false
                break
            }
            let path = URL.init(string: fileURL!)
            if (path == nil) {
                canAdd = false
                break
            }
            let type = path!.pathExtension.lowercased()
            if (KMTools.isPDFType(type) || KMTools.isImageType(type) || KMTools.isOfficeType(type)) {} else {
                canAdd = false
                self.delete?.homeDragView(self, notSupport: true)
                break
            }
        }
        
        if (canAdd) {
            dragEntered(true)
            return .every
        }
        
        self.layer?.borderColor = .clear
        return []
    }
    
    override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
        let pboard = sender.draggingPasteboard
        if (pboard.pasteboardItems == nil) {
            dragEntered(false)
            return true
        }
        
        for item in pboard.pasteboardItems! {
            let fileURL = item.string(forType: .fileURL)
            if (fileURL == nil) {
                continue
            }
            let path = URL.init(string: fileURL!)
            if (path == nil) {
                continue
            }
            
            self.delete?.homeDragView(self, filePath: path!)
        }
        
        dragEntered(false)
        return true
    }
    
    // MARK: Draw

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        
        if isDraggingEntered {
//            let path = NSBezierPath()
//            path.move(to: CGPoint(x: 0, y: 0))
//            path.line(to: CGPoint(x: 0, y: self.bounds.height))
//
//            path.move(to: CGPoint(x: 0, y: self.bounds.height))
//            path.line(to: CGPoint(x: self.bounds.width, y: self.bounds.height))
//
//            path.move(to: CGPoint(x: self.bounds.width, y: self.bounds.height))
//            path.line(to: CGPoint(x: self.bounds.width, y: 0))
//
//            path.move(to: CGPoint(x: self.bounds.width, y: 0))
//            path.line(to: CGPoint(x: 0, y: 0))
            let path = NSBezierPath(roundedRect: self.bounds, xRadius: 16.0, yRadius: 16.0)
            
            path.setLineDash([3, 3, 3], count: 3, phase: 0)
            path.lineWidth = 2.0
            NSColor.km_init(hex: "#68ACF8").setStroke()
            path.stroke()
        }
    }
    
}