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

import UIKit
import Kingfisher

open class KMAdvertisementShowView_iOS: KMAdvertisementBaseView {

    @IBOutlet var contentView: UIView!
    
    @IBOutlet weak var imageView: UIImageView!
    
    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: UIView) {
        self.init(frame: superView.bounds)
        
        superView.addSubview(self)
        self.autoresizingMask = [.flexibleHeight , .flexibleWidth]
        
        self.inputData = data
        self.reloadData()
    }
    
    // MARK: 初始化
    public required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        initContentView()
        setup()
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        initContentView()
        setup()
    }

    private func initContentView() {
        //绑定xib
        let resource = UINib(nibName: String(describing: self.classForCoder.self),
                             bundle: Bundle(for: self.classForCoder.self))
        resource.instantiate(withOwner: self)
        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.updateConstraintsIfNeeded()
    }
    
    func setup() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(buttonAction))
        self.imageView.addGestureRecognizer(tap)
        self.imageView.isUserInteractionEnabled = true
        self.addTimer()
    }
    
    func reloadData() {
        self.data.removeAll()
        let array = inputData.content!
        for section in array {
            for item in section.content! {
                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))
                self.imageView.kf.setImage(with: url)
            }
        }
    }
    
    @objc func buttonAction() {
        if self.data.count > index {
            let content = self.data[index]
            if actionCompletion != nil {
                actionCompletion!(.tap, content)
            }
        }
    }
}
