//
//  IdentityProvider.swift
//  AppleTVE
//
//  Copyright © 2016 Apple, Inc. All rights reserved.
//

import Foundation

struct IdentityProvider {
    let identifier : String
    let name : String
    
    init(identifier: String, name: String) {
        self.identifier = identifier
        self.name = name
    }
    
    func identifierIs(_ identifier: String) -> Bool {
        return (self.identifier == identifier || self.name == identifier)
    }
    
    func encodedName() -> String {
        return self.name.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
    }
}


struct IdentityProviderList {
    static let fileName = "IdentityProviderList"
    static let rootKey = "idplist"
    static let nameKey = "name"
    static let idKey = "identifier"
    
    static var identityProviders : Array<IdentityProvider> = []
    
    static func loadIdentityProviders() {
        if let idpList = Bundle.main.url(forResource: self.fileName, withExtension: "plist") {
            let idpDict = NSDictionary(contentsOf: idpList)
            
            (idpDict?.object(forKey: self.rootKey) as! NSArray).enumerateObjects({ (obj, index, stop) in
                let name = (obj as AnyObject).object(forKey: self.nameKey) as! String
                let identifier = (obj as AnyObject).object(forKey: self.idKey) as! String
                let idp = IdentityProvider(identifier: identifier, name: name)
                identityProviders.append(idp)
            })
        }
    }
    
    static func identityProviderForId(_ identifier: String) -> IdentityProvider? {
        let idp = identityProviders.first(where: { (idp) -> Bool in
            return idp.identifierIs(identifier)
        })
        
        return idp
    }
}
