//
//  UnifiedBiddingPresenter.swift
//  sdk-demo-ios
//
//  Created by Smaato Inc on 03/03/2019.
//  Copyright © 2019 Smaato Inc. All rights reserved.
//

import Foundation
import MoPub
import GoogleMobileAds

let ubSmaatoBannerAdSpaceId = "130563103"
let ubSmaatoInterstitialAdSpaceId = "130560861"
let ubSmaatoRewardedAdSpaceId = "130560861"

@objc class UnifiedBiddingPresenter: NSObject {

    var mopubData: [MopubModel] = [
        MopubModel(moPubsize: .bannerSize, adType: .Banner, adSpaceId: "5cd3496c673143a7a7a6a064b50ed440", name: "Banner", isCustom: false),
        MopubModel(moPubsize: nil, adType: .Interstitial, adSpaceId: "9e92c0d5c51a48e8bd6e021a207d4653", name: "Interstitial", isCustom: false),
        MopubModel(moPubsize: nil, adType: .Rewarded, adSpaceId: "34a47404e7be4835829994d2c4960507", name: "Rewarded", isCustom: false),
    ]

    var mopubModels: [MopubModel] {
        get {
            if (UserDefaults.standard.object(forKey: "UbMoPubAds") != nil) {
                if let modelsArray = UserDefaults.standard.array(forKey: "UbMoPubAds") as? [[String: Any]] {
                    mopubData = modelsArray.compactMap {
                        MopubModel(dictionary: $0)!
                    }
                }
            }

            return mopubData
        }

        set(newValue) {
            let models = newValue.map {
                $0.propertyListRepresentation
            }
            UserDefaults.standard.set(models, forKey: "UbMoPubAds")
            mopubData = newValue
        }
    }

    var onNewAdModel: (() -> ())?

    func add(mopubAdModel adSpaceId: String, name: String, adType: AdType, size: MoPubBannerSizes? = nil) {
        let model = MopubModel(moPubsize: size, adType: adType, adSpaceId: adSpaceId, name: name, isCustom: true)
        mopubModels.append(model)

        guard let newModelNotification = onNewAdModel else {
            return
        }
        newModelNotification()
    }
}

