//
//  RewardedAdViewController.swift
//  DemoApp
//
//  Created by Smaato Inc on 18.04.18.
//  Copyright © 2018 Smaato Inc. All rights reserved.
//

import UIKit
import SmaatoSDKRewardedAds
import SmaatoSDKCore


enum RewardedAdsTip: String {
    case TryLoadTip = "Tap ‘Load’ to load a rewarded ad"
    case LoadingTip = "Rewarded ad is loading…"
    case LoadedTip = "Rewarded ad was loaded successfully"
    case ErrorTip = "Something failed. See console logs"
    case ExpiredTip = "The loaded rewarded ad is expired. Tap ‘Load’ to load a new rewarded ad."
    case LoadNew = "Tap ‘Load’ again to load a new rewarded ad. The old rewarded ad could not be shown a second time"
    case NoTip = ""
}

class RewardedAdViewController: UIViewController {

    // Use own publisherId and adSpaceId from Dashboard settings to verify your ads
    // publisherId = "1100042525" and adSpaceId = "130626428" are default values for test ads presentation
    public var adSpaceId: String!

    // Rewarded ad object
    private var rewardedInterstitial: SMARewardedInterstitial?

    // Helper UI controls
    @IBOutlet private weak var buttonShow: UIButton!
    @IBOutlet private weak var publisherIdLabel: UILabel!
    @IBOutlet private weak var adspaceIdLabel: UILabel!
    @IBOutlet private weak var adBlock: AdBlockView!
    @IBOutlet private weak var scrollView: UIScrollView!

    @IBOutlet private weak var rewardedAdDidLoadLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidFailLabel: UILabel!
    @IBOutlet private weak var rewardedAdWillAppearLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidAppearLabel: UILabel!
    @IBOutlet private weak var rewardedAdWillDisappearLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidDisappearLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidTTLExpireLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidStartLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidRewardLabel: UILabel!
    @IBOutlet private weak var rewardedAdWillLeaveApplicationLabel: UILabel!

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

    //MARK: Actions

    @IBAction private func btnLoadTapped(_ sender: Any) {
        resetLabels()
        loadRewardedAd()
    }

    @IBAction private func btnShowTapped(_ sender: Any) {
        showRewardedAd()
    }

    //MARK: Private

    private func setupUI() {
        adBlock.tip = RewardedAdsTip.TryLoadTip.rawValue
        publisherIdLabel.text = SmaatoSDK.publisherId
        adspaceIdLabel.text = adSpaceId

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

    private func loadRewardedAd() {
        rewardedInterstitial = nil
        adBlock.tip = RewardedAdsTip.LoadingTip.rawValue

        //Send load rewarded ad request
        SmaatoSDK.loadRewardedInterstitial(forAdSpaceId: adSpaceId, delegate: self)
    }

    private func showRewardedAd() {
        // Try to show rewarded ad, if it has been already downloaded and is not expired (TTL value)
        if rewardedInterstitial?.availableForPresentation == true {
            rewardedInterstitial?.show(from: self)
        }
    }

    private func resetLabels() {
        rewardedAdDidLoadLabel.alpha = 0.2
        rewardedAdDidFailLabel.alpha = 0.2
        rewardedAdWillAppearLabel.alpha = 0.2
        rewardedAdDidAppearLabel.alpha = 0.2
        rewardedAdWillDisappearLabel.alpha = 0.2
        rewardedAdDidDisappearLabel.alpha = 0.2
        rewardedAdDidTTLExpireLabel.alpha = 0.2
        rewardedAdDidStartLabel.alpha = 0.2
        rewardedAdDidRewardLabel.alpha = 0.2
        rewardedAdWillLeaveApplicationLabel.alpha = 0.2
    }
}

// Implementation of SMARewardedInterstitialDelegate protocol
extension RewardedAdViewController: SMARewardedInterstitialDelegate {

    //MARK: Required methods

    func rewardedInterstitialDidLoad(_ rewardedInterstitial: SMARewardedInterstitial) {
        print("\(rewardedInterstitial) is available for presentation")
        resetLabels()
        rewardedAdDidLoadLabel.alpha = 1
        self.rewardedInterstitial = rewardedInterstitial
        adBlock.tip = RewardedAdsTip.LoadedTip.rawValue
        buttonShow.isEnabled = true
    }

    func rewardedInterstitialDidFail(_ rewardedInterstitial: SMARewardedInterstitial?, withError error: Error) {
        guard let hiddenError = (error as NSError).userInfo["NSUnderlyingError"] as? Error else {
            adBlock.tip = RewardedAdsTip.ErrorTip.rawValue
            return
        }
        NSLog("Hidden error: " + hiddenError.localizedDescription)
        rewardedAdDidFailLabel.alpha = 1
    }

    func rewardedInterstitialDidTTLExpire(_ rewardedInterstitial: SMARewardedInterstitial) {
        rewardedAdDidTTLExpireLabel.alpha = 1
        buttonShow.isEnabled = false
        adBlock.tip = RewardedAdsTip.ExpiredTip.rawValue
        NSLog("\(rewardedInterstitial) did TTL expire")
    }

    func rewardedInterstitialDidReward(_ rewardedInterstitial: SMARewardedInterstitial) {
        rewardedAdDidRewardLabel.alpha = 1
        NSLog("\(rewardedInterstitial) did reward")
    }

    //MARK: Optional methods

    func rewardedInterstitialWillAppear(_ rewardedInterstitial: SMARewardedInterstitial) {
        rewardedAdWillAppearLabel.alpha = 1
        NSLog("\(rewardedInterstitial) will appear")
    }

    func rewardedInterstitialDidAppear(_ rewardedInterstitial: SMARewardedInterstitial) {
        rewardedAdDidAppearLabel.alpha = 1
        NSLog("\(rewardedInterstitial) did appear")
    }

    func rewardedInterstitialWillDisappear(_ rewardedInterstitial: SMARewardedInterstitial) {
        rewardedAdWillDisappearLabel.alpha = 1
        NSLog("\(rewardedInterstitial) will disappear")
        adBlock.tip = RewardedAdsTip.LoadNew.rawValue
    }

    func rewardedInterstitialDidDisappear(_ rewardedInterstitial: SMARewardedInterstitial) {
        rewardedAdDidDisappearLabel.alpha = 1
        NSLog("\(rewardedInterstitial) did disappear")
        buttonShow.isEnabled = false
    }

    func rewardedInterstitialDidStart(_ rewardedInterstitial: SMARewardedInterstitial) {
        rewardedAdDidStartLabel.alpha = 1
        NSLog("\(rewardedInterstitial) did start")
    }

    func rewardedInterstitialWillLeaveApplication(_ rewardedInterstitial: SMARewardedInterstitial) {
        rewardedAdWillLeaveApplicationLabel.alpha = 1
        NSLog("\(rewardedInterstitial) will leave application")
    }
}
