import UIKit
import AdViewSDK

fileprivate let nativeStoredImpression = "POSID06zhclyweype"

class InAppNativeViewController: NativeBaseViewController {

    private var nativeUnit: AdViewNativeRequest!
    private var nativeAd: NativeAd?

    override func viewDidLoad() {
        super.viewDidLoad()
        applyFeedNativeLayout()
        createAd()
    }

    override func loadView() {
        super.loadView()
    }

    func createAd() {
    
        nativeUnit = AdViewNativeRequest(
            configId: nativeStoredImpression
        )
        
        nativeUnit.context = ContextType.Social
        nativeUnit.placementType = PlacementType.FeedContent
        nativeUnit.contextSubType = ContextSubType.Social

        nativeUnit.fetchDemand { [weak self] bidInfo in
            guard let self else { return }

            let cacheId = bidInfo.targetingKeywords?["hb_cache_id_local"] as? String
            guard let cacheId, let nativeAd = NativeAd.create(cacheId: cacheId) else {
                return
            }

            self.nativeAd = nativeAd
            self.titleLabel.text = nativeAd.title
            self.bodyLabel.text = nativeAd.text
            self.updateCallToActionButtonTitle(nativeAd.callToAction)
            self.sponsoredLabel.text = nativeAd.sponsoredBy

            if let iconUrl = nativeAd.iconUrl, let url = URL(string: iconUrl) {
                URLSession.shared.dataTask(with: url) { data, _, _ in
                    guard let data, let image = UIImage(data: data) else { return }
                    DispatchQueue.main.async {
                        self.iconView.image = image
                    }
                }.resume()
            }

            if let imageUrl = nativeAd.imageUrl, let url = URL(string: imageUrl) {
                URLSession.shared.dataTask(with: url) { data, _, _ in
                    guard let data, let image = UIImage(data: data) else { return }
                    DispatchQueue.main.async {
                        self.mainImageView.image = image
                        self.invalidateNativeMainImageLayoutIfNeeded()
                    }
                }.resume()
            }

            nativeAd.registerView(
                view: self.view,
                clickableViews: [self.callToActionButton, self.mainImageView, self.iconView]
            )
 
        }
    }
}
