//
//  GetContactBehavior.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 3/22/21.
//  Copyright © 2021 Verizon Wireless. All rights reserved.
//

import Foundation
import Contacts


public protocol PageGetContactBehaviorConsumerProtocol {
    func getMatchParameters() -> (NSPredicate, [CNKeyDescriptor])?
    func consume(contacts: [CNContact])
}

public class PageGetContactBehaviorModel: PageBehaviorModelProtocol {
    public class var identifier: String { "pageGetContactBehavior" }
    public var shouldAllowMultipleInstances: Bool { false }
    
    public init() { }
}

public class PageGetContactBehavior: PageVisibilityBehavior {
    
    var delegate: MVMCoreUIDelegateObject?
    
    public required init(model: PageBehaviorModelProtocol, delegateObject: MVMCoreUIDelegateObject?) {
        self.delegate = delegateObject
    }
    
    public func onPageShown(_ delegateObject: MVMCoreUIDelegateObject?) {
        // Ask for permission
        CNContactStore().requestAccess(for: .contacts) { [weak self] (access, error) in
            guard access,
                  error == nil,
                  let rootMolecules = self?.delegate?.moleculeDelegate?.getRootMolecules() else { return }
            // Iterate models and provide contact
            self?.getContacts(for: rootMolecules)
            
            // Tell template to update
            MVMCoreDispatchUtility.performBlock(onMainThread: {
                // TODO: move to protocol function instead
                guard let controller = self?.delegate?.moleculeDelegate as? ViewController else { return }
                controller.handleNewDataAndUpdateUI()
            })
        }
    }
    
    public func getContacts(for molecules: [MoleculeModelProtocol]) {
        let consumers: [PageGetContactBehaviorConsumerProtocol] = molecules.allMoleculesOfType()
        let store = CNContactStore()
        for consumer in consumers {
            guard let parameters = consumer.getMatchParameters(),
                  let contacts = try? store.unifiedContacts(matching: parameters.0, keysToFetch: parameters.1) else { return }
            consumer.consume(contacts: contacts)
        }
    }
    
    public func onPageHidden(_ delegateObject: MVMCoreUIDelegateObject?) {}
}
