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

import Foundation

class RewardedAdsPresenter: AdPresenting {

    var rewardedModels : [RewardedAdModel] = [RewardedAdModel(publisherId: "0", adSpaceId: "3090", name: "Simple rewarded interstitial", isCustom: false)]
    
    var models: [AdModel] {
        get {
            if (UserDefaults.standard.object(forKey: AdType.Rewarded.identifier) != nil) {
                if let modelsArray = UserDefaults.standard.array(forKey: AdType.Rewarded.identifier) as? [[String:Any]] {
                    rewardedModels = modelsArray.map { RewardedAdModel(dictionary: $0)! }
                }
            }
            
            return rewardedModels
        }
        
        set(newValue){
            let models = newValue.map{ $0.propertyListRepresentation }
            UserDefaults.standard.set(models, forKey: AdType.Rewarded.identifier)
            rewardedModels = newValue as! [RewardedAdModel]
        }
    }
    
    var onNewAdModel: (() -> ())?
    
    func add(adModel publisherId: String, adSpaceId: String, name: String) {
        let rewardedAdModel = RewardedAdModel(publisherId: publisherId, adSpaceId: adSpaceId, name: name, isCustom: true)
        models.append(rewardedAdModel)
        
        guard let newRewardedAdModelNotification = onNewAdModel else {
            return
        }
        newRewardedAdModelNotification()
    }
    
}
