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

import Foundation
import MoPub
import SmaatoSDKUnifiedBidding

class UbMoPubInterstitialViewController: UIViewController {
    
    @IBOutlet private weak var showButton: UIButton!
    @IBOutlet private weak var adBlock: AdBlockView!
    @IBOutlet private weak var adUnitIDLabel: UILabel!
    @IBOutlet private weak var adapterVersionLabel: UILabel!
    
    @IBOutlet private weak var interstitialDidLoadLabel: UILabel!
    @IBOutlet private weak var interstitialDidFailLabel: UILabel!
    @IBOutlet private weak var interstitialWillAppearLabel: UILabel!
    @IBOutlet private weak var interstitialDidAppearLabel: UILabel!
    @IBOutlet private weak var interstitialWillDisappearLabel: UILabel!
    @IBOutlet private weak var interstitialDidDisappearLabel: UILabel!
    @IBOutlet private weak var interstitialDidReceiveTapEventLabel: UILabel!
    @IBOutlet private weak var interstitialDidExpireLabel: UILabel!
    @IBOutlet private weak var scrollView: UIScrollView!
    
    private var interstitialController: MPInterstitialAdController!
    
    var mopubModel: MopubUBModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        interstitialController = MPInterstitialAdController(forAdUnitId: mopubModel.adUnitId)
        interstitialController.delegate = self
    }
    
    @IBAction func loadInterstitialTapped(_ sender: UIButton) {
        resetLabels()
        adBlock.tip = MediationInterstitialAdsTip.LoadingTip.rawValue
        
        SmaatoSDK.prebidInterstitial(forAdSpaceId: mopubModel.smaatoAdspaceId) { [weak self] (bid: SMAUbBid?, error: Error?) in
            if let smaatoBid = bid {
                let bidKeyword = smaatoBid.mopubPrebidKeyword
                self?.interstitialController.keywords = bidKeyword
            } else {
                print("SmaatoSDK PreBid error: \(String(describing: error?.localizedDescription))")
            }
            
            self?.interstitialController.loadAd()
        }

    }
    
    @IBAction func showInterstitialTapped(_ sender: UIButton) {
        showButton.isEnabled = false
        if interstitialController.ready {
            interstitialController.show(from: self)
        } else {
            NSLog("Interstitial ad is not ready.");
        }
    }
    
    //MARK: Private
    
    private func setupUI() {
        self.title = "MoPub Interstitial"
        adapterVersionLabel.text = "Adapter version \(SMAMoPubSmaatoInterstitialAdapter.version() ?? "")"
        adBlock.tip = MediationInterstitialAdsTip.TryLoadTip.rawValue
        adUnitIDLabel.text = mopubModel.adUnitId
        if #available(iOS 11.0, *) {
            scrollView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
            automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    private func resetLabels() {
        interstitialDidLoadLabel.alpha = 0.2
        interstitialDidFailLabel.alpha = 0.2
        interstitialWillAppearLabel.alpha = 0.2
        interstitialDidAppearLabel.alpha = 0.2
        interstitialWillDisappearLabel.alpha = 0.2
        interstitialDidDisappearLabel.alpha = 0.2
        interstitialDidReceiveTapEventLabel.alpha = 0.2
        interstitialDidExpireLabel.alpha = 0.2
    }
}

extension UbMoPubInterstitialViewController: MPInterstitialAdControllerDelegate {
    
    func interstitialDidLoadAd(_ interstitial: MPInterstitialAdController!) {
        NSLog("\(String(describing: interstitial)) did load")
        resetLabels()
        showButton.isEnabled = true
        adBlock.tip = MediationInterstitialAdsTip.LoadedTip.rawValue
        interstitialDidLoadLabel.alpha = 1
    }
    
    func interstitialWillAppear(_ interstitial: MPInterstitialAdController!) {
        interstitialWillAppearLabel.alpha = 1
    }
    
    func interstitialDidAppear(_ interstitial: MPInterstitialAdController!) {
        NSLog("\(String(describing: interstitial)) did appear")
        interstitialDidAppearLabel.alpha = 1
    }
    
    func interstitialWillDisappear(_ interstitial: MPInterstitialAdController!) {
        NSLog("\(String(describing: interstitial)) will disappear")
        adBlock.tip = MediationInterstitialAdsTip.LoadNew.rawValue
        interstitialWillDisappearLabel.alpha = 1
    }
    
    func interstitialDidReceiveTapEvent(_ interstitial: MPInterstitialAdController!) {
        NSLog("\(String(describing: interstitial)) did receive tap event")
        adBlock.tip = MediationInterstitialAdsTip.ClickedTip.rawValue
        interstitialDidReceiveTapEventLabel.alpha = 1
    }
    
    func interstitialDidDisappear(_ interstitial: MPInterstitialAdController!) {
        NSLog("\(String(describing: interstitial)) did disappear")
        interstitialDidDisappearLabel.alpha = 1
    }
    
    func interstitialDidExpire(_ interstitial: MPInterstitialAdController!) {
        NSLog("\(String(describing: interstitial)) did expire")
        showButton.isEnabled = false
        adBlock.tip = MediationInterstitialAdsTip.ExpiredTip.rawValue
        interstitialDidExpireLabel.alpha = 1
    }
    
    func interstitialDidFail(toLoadAd interstitial: MPInterstitialAdController!, withError error: Error!) {
        NSLog("\(String(describing: interstitial)) did fail with error \(error.localizedDescription)")
        adBlock.tip = MediationInterstitialAdsTip.ErrorTip.rawValue
        interstitialDidFailLabel.alpha = 1
    }
    
    func interstitialDidFail(toLoadAd interstitial: MPInterstitialAdController!) {
        NSLog("\(String(describing: interstitial)) did fail")
        adBlock.tip = MediationInterstitialAdsTip.ErrorTip.rawValue
        interstitialDidFailLabel.alpha = 1
    }
}
