//
//  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!
    
    lazy var presenter: KMAdvertisementTableViewPresenter! = KMAdvertisementTableViewPresenter()
    
    //内部使用数据
    fileprivate var data: [KMAdvertisementModel.Section]?
    /**
      @abstract 外部传入数据
      @param inputData 文件路劲
      */
    open var inputData: KMAdvertisementModel! {
        didSet {
            self.presenter.initPresenter(view: self, data: inputData)
        }
    }
    
    convenience init (data: KMAdvertisementModel, superView: UIView) {
        self.init(frame: superView.bounds)
        self.presenter.initPresenter(view: self, data: data)
        superView.addSubview(self)
        self.autoresizingMask = [.flexibleHeight , .flexibleWidth]
    }
    
    // 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
       }
    
    func reloadData() {
        let url = URL(string: self.data?.first?.content.first?.imageURL?.normal?.en ?? "")
        self.imageView.kf.setImage(with: url)
    }
    
    @objc func buttonAction() {
        let content = self.data?.first?.content.first
        if actionCompletion != nil {
            actionCompletion!(content!)
        }
    }
}

extension KMAdvertisementShowView_iOS: KMAdvertisementTableViewPresenterDelegate {
    func showData(presenter: KMAdvertisementTableViewPresenter, data: Array<KMAdvertisementModel.Section>) {
        self.data = data
        self.reloadData()
    }
}
