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

import UIKit
import MoPubSDK
import GoogleMobileAds
import SmaatoSDKCore
import SmaatoSDKUnifiedBidding
import SmaatoSDKInterstitial

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        setupAppearance()
        setupSmaatoSDK()
        setupMoPubSDK()
        setupAdMobSDK()

        if let splashAdValue = UserDefaults.standard.value(forKey: Constants.splashAdKey) as? String,
           splashAdValue == "1" {
            callSplashAd()
        }

        return true
    }
}

private extension AppDelegate {

    private func setupSmaatoSDK() {
        // Use own publisherId from Dashboard settings to verify your ads
        let config = SMAConfiguration.init(publisherId: "1100042525")!
        
        // Fetching user persisted data
        let userData = UserData.getSmaatoUserSettings()
        
        // You can change 'httpsOnly' flag in SettingsViewController view controller. By default httpsOnly = false in this application
        config.httpsOnly = userData.httpsOnly
        config.loggingDisabled = false
        config.logLevel = .verbose
        
        SmaatoSDK.userGender = userData.gender
        SmaatoSDK.userSearchQuery = userData.query
        SmaatoSDK.userKeywords = userData.keywords
        
        if let age = userData.age {
            SmaatoSDK.userAge = age as NSNumber
        }

        SmaatoSDK.gpsEnabled = true
        SmaatoSDK.initSDK(withConfig: config)

        // You can change 'requireCoppaCompliantAds' flag in SettingsViewController view controller. By default requireCoppaCompliantAds = false in this application
        SmaatoSDK.requireCoppaCompliantAds = UserDefaults.standard.bool(forKey: "MySavedCoppaSettings")
    }

    private func setupAppearance() {
        let navigationBar = UINavigationBar.appearance()
        navigationBar.isTranslucent = true
        navigationBar.barTintColor = .appColor
        navigationBar.tintColor = UIColor.white

        navigationBar.shadowImage = UIImage()

        navigationBar.titleTextAttributes =
                [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.white]
        if #available(iOS 11.0, *) {
            navigationBar.largeTitleTextAttributes =
                    [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.white]
        }

    }

    private func setupMoPubSDK() {
        let sdkConfig = MPMoPubConfiguration(adUnitIdForAppInitialization: "17c9566ad386405db78c5447dc93c75d")
        sdkConfig.globalMediationSettings = []
        sdkConfig.loggingLevel = .info
        MoPub.sharedInstance().initializeSdk(with: sdkConfig, completion: {
            print("MoPub initialization complete")
        })
    }
 
    private func setupAdMobSDK() {
        GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers =  [(kGADSimulatorID as! String)]
        GADMobileAds.sharedInstance().start()
    }

    private func callSplashAd() {
        let params = SMAAdRequestParams()
        params.isSplash = true
        SmaatoSDK.loadInterstitial(forAdSpaceId: "130626426", delegate: self, requestParams: params)
    }
}

extension AppDelegate: SMAInterstitialDelegate {
    func interstitialDidLoad(_ interstitial: SMAInterstitial) {
        print("Splash ad did load: %@", interstitial)
    }
    
    func interstitial(_ interstitial: SMAInterstitial?, didFailWithError error: Error) {
        print("Splash ad failed with error: %@", error)
    }
    
    func interstitialDidTTLExpire(_ interstitial: SMAInterstitial) {
        print("Splash ad TTL expired: %@", interstitial)
    }
}
