//
//  KMLightMemberAlertView.swift
//  PDF Master
//
//  Created by lizhe on 2023/2/24.
//

import Cocoa

class KMLightMemberAlertView: KMBaseXibView {

    @IBOutlet weak var titleLabel: NSTextField!
    @IBOutlet weak var titleContentView: NSView!
    
    var timer: DispatchSourceTimer?
    
    var result: Result = Result() {
        didSet {
            self.alphaValue = 1.0
            self.reloadData()
        }
    }
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }
    
    override func setup() {
        super.setup()
        self.result = Result(code: 0)

    }
    
    override func updateUI() {
        super.updateUI()
        self.contentView.backgroundColor(NSColor(hex: "#FDC7C6"))
        
        self.titleLabel.font = NSFont.SFProTextRegular(14.0)
        self.titleLabel.textColor = NSColor(hex: "#252629")
    }
    
    override func reloadData() {
        super.reloadData()
        
        if result.code == 200 || result.code == 0 {
            self.contentView.isHidden = true
        } else {
            self.contentView.isHidden = false
        }
        
        self.titleLabel.stringValue = NSLocalizedString(KMRequestServerErrorCodeType.typeOfMessage(type: KMRequestServerErrorCodeType(rawValue: result.code)), comment: "")
        
        self.callMethodWithDelay()
    }
    
    func callMethodWithDelay() {
        // 取消之前的计时器
        timer?.cancel()

        // 创建一个新的计时器,延迟 2 秒
        timer = DispatchSource.makeTimerSource()
        timer?.schedule(deadline: .now() + 3, leeway: .milliseconds(10))
        timer?.setEventHandler(handler: { [unowned self] in
            // 2 秒后执行的代码
            methodToExecuteAfterDelay()
        })
        timer?.resume()
    }

    func methodToExecuteAfterDelay() {
        // 执行的代码
        self.fadeOut()
    }
    
    func fadeOut() {
        NSAnimationContext.runAnimationGroup({ (context) in
            context.duration = 1
            animator().alphaValue = 0.0
        }, completionHandler: nil)
    }
    override func updateLanguage() {
        super.updateLanguage()
    }
}