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

import Foundation

class BannersPresenter: AdPresenting {
    
    private var bannerModel: [BannerAdModel] = [BannerAdModel(size: .xxlarge, publisherId: "0", adSpaceId: "0", name: "Banner 320 x 50", isCustom: false),
                                         BannerAdModel(size: .medium, publisherId: "0", adSpaceId: "0", name: "Banner 320 x 250", isCustom: false),
                                         BannerAdModel(size: .leaderboard, publisherId: "0", adSpaceId: "0", name: "Banner 728 x 90", isCustom: false),
                                         BannerAdModel(size: .skyscraper, publisherId: "0", adSpaceId: "0", name: "Banner 120 x 600", isCustom: false)]
    
    var models: [AdModel] {
        get {
            if (UserDefaults.standard.object(forKey: AdType.Banner.identifier) != nil) {
                if let modelsArray = UserDefaults.standard.array(forKey: AdType.Banner.identifier) as? [[String:Any]] {
                    bannerModel = modelsArray.compactMap { BannerAdModel(dictionary: $0)! }
                }
            }
            
            if UIDevice.current.userInterfaceIdiom == .phone {
                return bannerModel.filter({ $0.size == .xxlarge || $0.size == .medium })
            }
            
            return bannerModel
        }
        
        set(newValue){
            let models = newValue.map{ $0.propertyListRepresentation }
            UserDefaults.standard.set(models, forKey: AdType.Banner.identifier)
            bannerModel = newValue as! [BannerAdModel]
        }
    }
    
    var onNewAdModel: (() -> ())?
    
    func add(adModel publisherId: String, adSpaceId: String, name: String, size: BannerSize) {
        let bannerModel = BannerAdModel(size: size, publisherId: publisherId, adSpaceId: adSpaceId, name: name, isCustom: true)
        models.append(bannerModel)
        
        guard let newBannerModelNotification = onNewAdModel else {
            return
        }
        newBannerModelNotification()
    }
}
