//
//  UbMoPubBannerViewController.swift
//  sdk-demo-ios
//
//  Created by Smaato Inc on 03/03/2019.
//  Copyright © 2019 Smaato Inc. All rights reserved.
//

import Foundation
import MoPub
import SmaatoSDKBanner
import SmaatoSDKUnifiedBidding

class UbMoPubBannerViewController: UIViewController {

    @IBOutlet private weak var adBlockView: AdBlockView!
    @IBOutlet private weak var adUnitIdLabel: UILabel!
    @IBOutlet private weak var adViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet private weak var adViewWidthConstraint: NSLayoutConstraint!
    @IBOutlet private weak var showButton: UIButton!
    @IBOutlet private weak var adapterVersionLabel: UILabel!
    @IBOutlet private weak var scrollView: UIScrollView!

    @IBOutlet private weak var bannerDidLoadLabel: UILabel!
    @IBOutlet private weak var bannerDidFailLabel: UILabel!
    @IBOutlet private weak var bannerWillPresentModalViewLabel: UILabel!
    @IBOutlet private weak var bannerDidDismissModalViewLabel: UILabel!
    @IBOutlet private weak var bannerWillLeaveAppLabel: UILabel!

    private var adView: MPAdView!

    var mopubModel: MopubModel!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()

        //Setup MPAdView
        adView = MPAdView(adUnitId: mopubModel.adSpaceId, size: adSize)
        adView.delegate = self
        adView.stopAutomaticallyRefreshingContents()
    }

    //MARK: Actions

    @IBAction private func buttonLoadTapped(_ sender: UIButton) {
        resetLabels()
        adBlockView.tip = MediationBannerAdsTip.LoadingTip.rawValue
        loadAd()
    }

    @IBAction private func buttonShowTapped(_ sender: UIButton) {
        showButton.isEnabled = false
        adBlockView.addSubview(adView)
    }

    //MARK: Private

    private var adSize: CGSize {
        get {
            switch mopubModel.moPubsize {
            case .bannerSize: return MOPUB_BANNER_SIZE
            case .medRectSize: return MOPUB_MEDIUM_RECT_SIZE
            case .leaderBoardSize: return MOPUB_LEADERBOARD_SIZE
            case .wideSkyscrapperSize: return MOPUB_WIDE_SKYSCRAPER_SIZE
            }
        }
    }

    private func setupUI() {
        adUnitIdLabel.text = mopubModel.adSpaceId
        adapterVersionLabel.text = "Adapter version \(SMAMoPubSmaatoBannerAdapter.version() ?? "")"
        adBlockView.tip = MediationBannerAdsTip.TryLoadTip.rawValue
        updateAdBlockSize()

        if #available(iOS 11.0, *) {
            scrollView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
            automaticallyAdjustsScrollViewInsets = false
        }
    }

    private func updateAdBlockSize() {
        adViewHeightConstraint.constant = adSize.height
        adViewWidthConstraint.constant = adSize.width
    }

    private func resetLabels() {
        bannerDidLoadLabel.alpha = 0.2
        bannerDidFailLabel.alpha = 0.2
        bannerWillPresentModalViewLabel.alpha = 0.2
        bannerDidDismissModalViewLabel.alpha = 0.2
        bannerWillLeaveAppLabel.alpha = 0.2
    }

    private func loadAd() {
        SmaatoSDK.prebidBanner(forAdSpaceId: ubSmaatoBannerAdSpaceId,
                bannerSize: .xxLarge_320x50) { [weak self] (bid: SMAUbBid?, error: Error?) in
            if let smaatoBid = bid {
                let bidKeyword = smaatoBid.mopubPrebidKeyword
                self?.adView.keywords = bidKeyword
            } else {
                print("SmaatoSDK PreBid error: \(String(describing: error?.localizedDescription))")
            }
                    
            self?.adView.loadAd()
        }

    }
}

extension UbMoPubBannerViewController: MPAdViewDelegate {

    func viewControllerForPresentingModalView() -> UIViewController! {
        return self
    }

    //MARK: Optional methods

    func adViewDidLoadAd(_ view: MPAdView!) {
        NSLog("\(String(describing: view))) did load")
        resetLabels()
        showButton.isEnabled = true
        adBlockView.tip = MediationBannerAdsTip.LoadedTip.rawValue
        bannerDidLoadLabel.alpha = 1
    }

    func adViewDidFail(toLoadAd view: MPAdView!) {
        NSLog("\(String(describing: view)) did fail to load")
        adBlockView.tip = MediationBannerAdsTip.ErrorTip.rawValue
        bannerDidFailLabel.alpha = 1
    }

    func didDismissModalView(forAd view: MPAdView!) {
        NSLog("\(String(describing: view)) did dismiss modal view")
        bannerDidDismissModalViewLabel.alpha = 1
    }

    func willPresentModalView(forAd view: MPAdView!) {
        NSLog("\(String(describing: view)) did will present modal view")
        bannerWillPresentModalViewLabel.alpha = 1
    }

    func willLeaveApplication(fromAd view: MPAdView!) {
        NSLog("\(String(describing: view)) will leave application")
        bannerWillLeaveAppLabel.alpha = 1
    }

}
