//
//  MoPubNativeViewController.swift
//  sdk-demo-ios
//
//  Created by Smaato Inc on 16.04.20.
//  Copyright © 2020 Smaato Inc. All rights reserved.
//

import Foundation
import MoPubSDK
import SmaatoSDKNative

enum MediationNativeAdsTip: String {
    case TryLoadTip = "Tap ‘Load’ to load Native Ad"
    case LoadingTip = "Native ad loading…"
    case LoadedTip = "Native ad loaded successfully"
    case ErrorTip = "Something failed. See console logs."
    case NoTip = ""
}

class MoPubNativeViewController: UIViewController {

    @IBOutlet private weak var adBlockView: AdBlockView!
    @IBOutlet private weak var adUnitIDLabel: UILabel!
    @IBOutlet private weak var showButton: UIButton!
    @IBOutlet private weak var adapterVersionLabel: UILabel!

    @IBOutlet private weak var nativeDidLoadLabel: UILabel!
    @IBOutlet private weak var nativeDidFailLabel: UILabel!
    @IBOutlet private weak var nativeWillPresentModalViewLabel: UILabel!
    @IBOutlet private weak var nativeDidDismissModalViewLabel: UILabel!
    @IBOutlet private weak var nativeWillLeaveAppLabel: UILabel!

    var mopubModel: MopubModel!
    var nativeAd: MPNativeAd?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    //MARK: Actions

    @IBAction private func buttonLoadTapped(_ sender: UIButton) {
        resetLabels()
        adBlockView.tip = MediationNativeAdsTip.LoadingTip.rawValue
        
        let settings = MPStaticNativeAdRendererSettings()
        settings.renderingViewClass = MoPubNativeAdapterAdView.self
        
        guard let config = MPStaticNativeAdRenderer.rendererConfiguration(with: settings) else { return }
        config.supportedCustomEvents = ["SMAMoPubSmaatoNativeAdapter"]
        
        let targeting = MPNativeAdRequestTargeting(creativeSafeSize: adBlockView.bounds.size)
        targeting.desiredAssets = [kAdTextKey, kAdTitleKey, kAdMainImageKey, kAdIconImageKey, kAdCTATextKey, kAdStarRatingKey]
        
        let adRequest = MopubBridgeClass.getRequestWithAdUnitIdentifier(mopubModel.adUnitId, rendererConfigurations: [config]) as? MPNativeAdRequest
        adRequest?.targeting = targeting
        adRequest?.start(completionHandler: { [weak self] (request, response, error) in
            
            guard let self = self else { return }
            
            if let _ = error {
                self.didFail()
            } else if let response = response {
                self.nativeAd = response
                self.nativeAd?.delegate = self
                self.showButton.isEnabled = true
                self.didSuccess()
            } else {
                self.didFail()
            }
        })
    }

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

        do {
            guard let nativeAdView = try self.nativeAd?.retrieveAdView() else { return }
            nativeAdView.frame = self.adBlockView.bounds
            for view in self.adBlockView.subviews {
                view.removeFromSuperview()
            }
            self.adBlockView.addSubview(nativeAdView)
        } catch {
            didFail()
            print(error)
        }
    }

    //MARK: Private

    private func didFail() {
        NSLog("\(String(describing: view)) did fail to load")
        adBlockView.tip = MediationNativeAdsTip.ErrorTip.rawValue
        nativeDidFailLabel.alpha = 1
    }
    
    private func didSuccess() {
        NSLog("\(String(describing: view))) did load")
        resetLabels()
        showButton.isEnabled = true
        adBlockView.tip = MediationNativeAdsTip.LoadedTip.rawValue
        nativeDidLoadLabel.alpha = 1
    }
    
    private func setupUI() {
        adUnitIDLabel.text = mopubModel.adUnitId
        adapterVersionLabel.text = "Adapter version \(SMAMoPubSmaatoNativeAdapter.version() ?? "")"
        adBlockView.tip = MediationNativeAdsTip.TryLoadTip.rawValue
    }

    private func resetLabels() {
        nativeDidLoadLabel.alpha = 0.2
        nativeDidFailLabel.alpha = 0.2
        nativeWillPresentModalViewLabel.alpha = 0.2
        nativeDidDismissModalViewLabel.alpha = 0.2
        nativeWillLeaveAppLabel.alpha = 0.2
    }
}

extension MoPubNativeViewController: MPNativeAdDelegate {
    
    func viewControllerForPresentingModalView() -> UIViewController! {
        return self
    }
    
    //MARK: Optional methods

    func willPresentModal(for nativeAd: MPNativeAd!) {
        NSLog("\(String(describing: view)) did will present modal view")
        nativeWillPresentModalViewLabel.alpha = 1
    }
    
    func didDismissModal(for nativeAd: MPNativeAd!) {
        NSLog("\(String(describing: view)) did dismiss modal view")
        nativeDidDismissModalViewLabel.alpha = 1
    }
    
    func willLeaveApplication(from nativeAd: MPNativeAd!) {
        NSLog("\(String(describing: view)) will leave application")
        nativeWillLeaveAppLabel.alpha = 1
    }
}
