//
//  KMAdvertisementShowView.swift
//  KMAdvertisement
//
//  Created by lizhe on 2022/11/29.
//

import Cocoa
@objcMembers open class KMAdvertisementShowView: KMAdvertisementBaseView {

    @IBOutlet var contentView: NSView!
    
    @IBOutlet weak var cancelButton: NSButton!
    
    @IBOutlet weak var imageView: NSImageView!
    
    var timer: Timer?
    var index: Int = 0
    
    //内部使用数据
    fileprivate var data: [KMAdvertisementModelItem] = []
    /**
      @abstract 外部传入数据
      @param inputData 文件路劲
      */
    open var inputData: KMAdvertisementModel? {
        didSet {
            self.reloadData()
        }
    }
    
    convenience init (data: KMAdvertisementModel, superView: NSView) {
        self.init(frame: superView.bounds)
        superView.addSubview(self)
        self.autoresizingMask = [.height , .width]
        
        self.inputData = data
        self.reloadData()
    }
    
    // MARK: 初始化
    public required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        initContentView()
        setup()
    }
    
    public override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        initContentView()
        setup()
    }
    

    private func initContentView() {
        //绑定xib
        let resource = NSNib(nibNamed: String(describing: self.classForCoder.self),
                             bundle: Bundle(for: self.classForCoder.self))!
        resource.instantiate(withOwner: self, topLevelObjects: nil)
        addSubview(contentView)
        contentView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            contentView.topAnchor.constraint(equalTo: topAnchor),
            contentView.leftAnchor.constraint(equalTo: leftAnchor),
            contentView.rightAnchor.constraint(equalTo: rightAnchor),
            contentView.bottomAnchor.constraint(equalTo: bottomAnchor)])
        contentView.updateConstraintsForSubtreeIfNeeded()
    }
    
    func setup() {
        let bundle = Bundle(for: self.classForCoder.self)
        let path = bundle.path(forResource: "KMAdvertisement", ofType: "bundle") ?? ""
        let sdkBundle = Bundle(path: path)
        let filePath = sdkBundle?.pathForImageResource("ad_cancel_button00")
        let image = NSImage.init(contentsOfFile: filePath!)
        self.cancelButton.image = image
        self.addTimer()
    }
    
    public override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }
    
    func reloadData() {
        if inputData != nil {
            if (UserDefaults.standard.object(forKey: "KMAdvertisementShowTypeView") == nil) {
                UserDefaults.standard.set([], forKey: "KMAdvertisementShowTypeView")
            }
            let cacheArray: [String] = UserDefaults.standard.object(forKey: "KMAdvertisementShowTypeView") as! [String]
            
            self.data.removeAll()
            let array = inputData!.content
            if array != nil {
                for section in array! {
                    for item in section.content! {
                        if !cacheArray.contains(item.productID!) {
                            self.data.append(item)
                        }
                    }
                }
            }
            
            if self.data.count == 0 {
                self.removeTimer()
                self.removeFromSuperview()
            }
            self.recordTime()
        }
    }
    
    //MARK: 定时器
    func addTimer() {
        self.removeTimer()
        timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector (recordTime),
        userInfo: nil, repeats: true)
        if let curTimer: Timer = timer {
            RunLoop.main.add(curTimer, forMode: .common)
        }
    }
    
    func removeTimer() {
        if (timer != nil) {
           timer?.invalidate ()
           timer = nil
        }
    }
    
    @objc func recordTime () {
        if self.data.count != 0 {
            index += 1
            if index >= self.data.count {
                index = 0
            }

            if self.data.count != 0 {
                let url = URL(string: KMAdvertisementModelTransition.transitionImagePath(image: self.data[index].imageURL!, highlight: false))
                weak var weakSelf = self
                self.imageView.image = KMAdvertisementImage.imageWithURL(url: url, completion: { image in
                    if weakSelf != nil {
                        weakSelf!.imageView.image = image
                    }
                })
            }
        }
    }
    
          
    @IBAction func cancelAction(_ sender: Any) {
        if self.data.count > index {
            let content = self.data[index]
            if actionCompletion != nil {
                actionCompletion!(.cancel, content)
            }
            
            self.data.remove(at: index)
            if self.data.count == 0 {
                self.removeFromSuperview()
            }
            
            if (UserDefaults.standard.object(forKey: "KMAdvertisementShowTypeView") == nil) {
                UserDefaults.standard.set([], forKey: "KMAdvertisementShowTypeView")
            }
            var array: [String] = UserDefaults.standard.object(forKey: "KMAdvertisementShowTypeView") as! [String]
            
            array.append(content.productID!)
            UserDefaults.standard.set(array, forKey: "KMAdvertisementShowTypeView")
            UserDefaults.standard.synchronize()
            self.recordTime()
        }
    }
    
    open override func mouseDown(with event: NSEvent) {
        if self.data.count > index {
            let content = self.data[index]
            if actionCompletion != nil {
                actionCompletion!(.tap, content)
            }
        }
    }
}
