//
//  KMSecureAlertView.swift
//  Cisdem PDFMaster
//
//  Created by lizhe on 2024/1/24.
//

import Cocoa

typealias KMSecureAlertViewCloseAction = (_ view: KMSecureAlertView) -> Void
typealias KMSecureAlertViewPasswordAction = (_ view: KMSecureAlertView) -> Void

class KMSecureAlertView: KMBaseXibView {
    @IBOutlet var tipsLabel: NSTextField!
    @IBOutlet var rightBox: NSBox!
    @IBOutlet var rightBtn: NSButton!

    var closeAction: KMSecureAlertViewCloseAction?
    var passwordAction: KMSecureAlertViewPasswordAction?
    
    var isClosePromptView: Bool = false

    override func setup() {
        self.wantsLayer = true
        self.layer?.backgroundColor = KMAppearance.Else.tipbarColor().cgColor

        self.tipsLabel.stringValue = NSLocalizedString("This document has a permission password.", comment: "")
        self.tipsLabel.textColor = KMAppearance.Layout.w0Color()
        self.rightBox.borderWidth = 1.0
        self.rightBox.borderColor = KMAppearance.Layout.w70Color()
        self.rightBtn.title = " \(NSLocalizedString("Enter Password", comment: ""))  "
        if self.rightBtn.responds(to: #selector(setter: NSButton.bezelColor)) {
            self.rightBtn.bezelColor = KMAppearance.Interactive.m0Color()
        }
    }

    @IBAction func closedAction(_ sender: Any) {
        self.isClosePromptView = true
        self.closeAction?(self)
        self.removeFromSuperview()
    }

    @IBAction func passwordAction(_ sender: Any) {
        self.passwordAction?(self)
    }

    func show(in pdfView: CPDFView) {
        if self.isClosePromptView || !pdfView.document!.isEncrypted {
            if self.superview != nil {
                self.removeFromSuperview()
            }
            return
        }
        DispatchQueue.main.async {
            self.frame = NSRect(x: 0, y: pdfView.frame.size.height - 40, width: pdfView.frame.size.width, height: 40)
            pdfView.addSubview(self)
            self.autoresizingMask = [.width, .minYMargin]
        }
    }
}