//
//  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: MopubUBModel!

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

        //Setup MPAdView
        adView = MPAdView(adUnitId: mopubModel.adUnitId)
        adView.delegate = self
        adView.stopAutomaticallyRefreshingContents()
    }

    //MARK: Actions

    @IBAction private func buttonLoadTapped(_ sender: UIButton) {
        resetLabels()
        adView.frame.size = self.adSize
        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 CGSize(width: 320, height: 50)
            case .medRectSize: return CGSize(width: 300, height: 250)
            case .leaderBoardSize: return CGSize(width: 728, height: 90)
            default:
                return .zero
            }
        }
    }
    
    private var ubSmaatoSize: SMAUbBannerSize {
        get {
            switch mopubModel.moPubsize {
            case .bannerSize: return .xxLarge_320x50
            case .medRectSize: return .mediumRectangle_300x250
            case .leaderBoardSize: return .leaderboard_728x90
            }
        }
    }

    private func setupUI() {
        adUnitIdLabel.text = mopubModel.adUnitId
        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: mopubModel.smaatoAdspaceId,
            bannerSize: ubSmaatoSize) { [weak self] (bid: SMAUbBid?, error: Error?) in
                if let smaatoBid = bid {
                    self?.adView.keywords = smaatoBid.mopubPrebidKeyword
                    self?.adView.localExtras = smaatoBid.metaData
                } 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
    }

}
