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

import UIKit
import SmaatoSDKBanner

enum BannerAdsTip: String {
    case TryLoadTip = "Tap ‘Load’ to load banner"
    case LoadingTip = "Banner loading…"
    case LoadedTip = "Banner loaded successfully"
    case ClickedTip = "Banner clicked"
    case ErrorTip = "Something failed. See console logs."
    case NoTip = ""
}

class BannerViewController: UIViewController {

    // Use own publisherId and adSpaceId from Dashboard settings to verify your ads
    // publisherId = "1100042525" and adSpaceId = "130626424" are default values for test ads presentation
    public var adSpaceId: String!
    public var adSize: SMABannerAdSize!
    public var expectedSize: CGSize?

    // Baner ad object
    private var bannerView: SMABannerView?

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

    @IBOutlet private weak var bannerDidLoadLabel: UILabel!
    @IBOutlet private weak var bannerDidFailLabel: UILabel!
    @IBOutlet private weak var bannerWillPresentModalContentLabel: UILabel!
    @IBOutlet private weak var bannerDidPresentModalContentLabel: UILabel!
    @IBOutlet private weak var bannerDidDismissModalContentLabel: UILabel!
    @IBOutlet private weak var bannerDidClickLabel: UILabel!
    @IBOutlet private weak var bannerDidTTLExpireLabel: UILabel!

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

    //MARK: Actions

    @IBAction private func btnLoadTapped(_ sender: Any) {
        resetLabels()
        guard let containerSize = expectedSize else {
            print("Banner size should be defined before request or after it")
            return
        }

        // Remove old banner from the screen if it exists
        bannerView?.removeFromSuperview()
        buttonShow.isEnabled = false
        adBlock.tip = BannerAdsTip.LoadingTip.rawValue

        // Create new banner view programatically
        let banner = SMABannerView.init(frame: CGRect(x: 0, y: 0, width: containerSize.width, height: containerSize.height))

        // Send request and listen to callbacks
        banner.delegate = self
        banner.load(withAdSpaceId: adSpaceId, adSize: adSize)

        bannerView = banner
    }

    @IBAction private func btnShowTapped(_ sender: Any) {
        guard let banner = bannerView else {
            print("Banner has not been loaded yet")
            return
        }
        buttonShow.isEnabled = false
        banner.autoreloadInterval = switchAutoReload.isOn ? .default : .disabled
        adBlock.addSubview(banner)
        adBlock.tip = BannerAdsTip.NoTip.rawValue
    }

    @IBAction private func enableDidSwitch(_ sender: Any) {
        //Seconds count before Ad is reloaded. Default value is 0 (Autoreload is disabled).
        bannerView?.autoreloadInterval = switchAutoReload.isOn ? .default : .disabled
    }

    //MARK: Private

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

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

    private func updateAdBlockSize() {
        if let size = expectedSize {
            adBlockWidthConstraint.constant = size.width
            adBlocHeightConstraint.constant = size.height
        }
    }

    func resetLabels() {
        bannerDidLoadLabel.alpha = 0.2
        bannerDidFailLabel.alpha = 0.2
        bannerWillPresentModalContentLabel.alpha = 0.2
        bannerDidPresentModalContentLabel.alpha = 0.2
        bannerDidDismissModalContentLabel.alpha = 0.2
        bannerDidClickLabel.alpha = 0.2
        bannerDidTTLExpireLabel.alpha = 0.2
    }
}

extension BannerViewController: SMABannerViewDelegate {

    //MARK: Required methods

    func presentingViewController(for bannerView: SMABannerView) -> UIViewController {
        return self
    }

    func bannerViewDidTTLExpire(_ bannerView: SMABannerView) {
        NSLog("\(bannerView) TTL has expired and you can not use this banner from now. Please load new one. Tip: show banner before expiration for the best fill rate (you have about 5 minutes after loading completion).")
        bannerDidTTLExpireLabel.alpha = 1
    }

    //MARK: Optional methods

    func bannerViewDidLoad(_ bannerView: SMABannerView) {
        buttonShow.isEnabled = true
        adBlock.tip = BannerAdsTip.LoadedTip.rawValue
        bannerDidLoadLabel.alpha = 1
        NSLog("\(bannerView) loaded successfully")
    }

    func bannerViewDidClick(_ bannerView: SMABannerView) {
        adBlock.tip = BannerAdsTip.ClickedTip.rawValue
        bannerDidClickLabel.alpha = 1
        NSLog("\(bannerView) has been clicked")
    }

    func bannerView(_ bannerView: SMABannerView, didFailWithError error: Error) {
        adBlock.tip = BannerAdsTip.ErrorTip.rawValue
        bannerDidFailLabel.alpha = 1
        NSLog("\(bannerView) failed with error: \(error)")
    }

    func bannerViewWillPresentModalContent(_ bannerView: SMABannerView) {
        bannerWillPresentModalContentLabel.alpha = 1
        NSLog("\(bannerView) will present a modal content")
    }

    func bannerViewDidPresentModalContent(_ bannerView: SMABannerView) {
        bannerDidPresentModalContentLabel.alpha = 1
        NSLog("\(bannerView) did present a modal content")
    }

    func bannerViewDidDismissModalContent(_ bannerView: SMABannerView) {
        bannerDidDismissModalContentLabel.alpha = 1
        NSLog("\(bannerView) did dissmiss a modal content")
    }
}

