//
//  InterstitialViewController.swift
//  sdk-demo-ios
//
//  Created by Smaato Inc on 16.11.18.
//  Copyright © 2018 Smaato Inc. All rights reserved.
//

import UIKit
import SmaatoSDKInterstitial

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


class InterstitialViewController: UIViewController {

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

    // Baner ad object
    private var interstitial: SMAInterstitial?

    // 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 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 interstitialDidClickLabel: UILabel!
    @IBOutlet private weak var interstitialDidTTLExpireLabel: UILabel!
    @IBOutlet private weak var interstitialWillLeaveAppLabel: UILabel!

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

    //MARK: Actions

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

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

    //MARK: Private

    private func setupUI() {
        adBlock.tip = InterstitialAdsTip.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 loadInterstitialAd() {
        interstitial = nil
        adBlock.tip = InterstitialAdsTip.LoadingTip.rawValue

        //Send load interstitial request
        SmaatoSDK.loadInterstitial(forAdSpaceId: adSpaceId, delegate: self)
    }

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

    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
        interstitialDidClickLabel.alpha = 0.2
        interstitialDidTTLExpireLabel.alpha = 0.2
        interstitialWillLeaveAppLabel.alpha = 0.2
    }
}

extension InterstitialViewController: SMAInterstitialDelegate {

    //MARK: Required methods

    func interstitialDidLoad(_ interstitial: SMAInterstitial) {
        resetLabels()
        self.interstitial = interstitial
        buttonShow.isEnabled = true
        adBlock.tip = InterstitialAdsTip.LoadedTip.rawValue
        interstitialDidLoadLabel.alpha = 1
    }

    func interstitial(_ interstitial: SMAInterstitial?, didFailWithError error: Error) {
        guard let hiddenError = (error as NSError).userInfo["NSUnderlyingError"] as? Error else {
            adBlock.tip = InterstitialAdsTip.ErrorTip.rawValue
            return
        }
        interstitialDidFailLabel.alpha = 1
        NSLog("Hidden error: " + hiddenError.localizedDescription)
    }

    func interstitialDidTTLExpire(_ interstitial: SMAInterstitial) {
        buttonShow.isEnabled = false
        adBlock.tip = InterstitialAdsTip.ExpiredTip.rawValue
        interstitialDidTTLExpireLabel.alpha = 1
        NSLog("\(interstitial) did expire")
    }

    //MARK: Optional methods

    func interstitialWillAppear(_ interstitial: SMAInterstitial) {
        interstitialWillAppearLabel.alpha = 1
        NSLog("\(interstitial) will appear")
    }

    func interstitialDidAppear(_ interstitial: SMAInterstitial) {
        interstitialDidAppearLabel.alpha = 1
        NSLog("\(interstitial) did appear")
    }

    func interstitialWillDisappear(_ interstitial: SMAInterstitial) {
        interstitialWillDisappearLabel.alpha = 1
        adBlock.tip = InterstitialAdsTip.LoadNew.rawValue
        NSLog("\(interstitial) will disappear")
    }

    func interstitialDidDisappear(_ interstitial: SMAInterstitial) {
        interstitialDidDisappearLabel.alpha = 1
        buttonShow.isEnabled = false
        NSLog("\(interstitial) did disappear")
    }

    func interstitialDidClick(_ interstitial: SMAInterstitial) {
        interstitialDidClickLabel.alpha = 1
        adBlock.tip = InterstitialAdsTip.ClickedTip.rawValue
        NSLog("\(interstitial) has been clicked")
    }

    func interstitialWillLeaveApplication(_ interstitial: SMAInterstitial) {
        interstitialWillLeaveAppLabel.alpha = 1
        NSLog("\(interstitial) will leave application")
    }
}
