import Foundation
import UIKit
import Contacts

@objc public class Contact: NSObject {
    
    @objc public func saveContact(name: String, phone: String, email: String, dept: String, ext: String, completion: @escaping (Bool) -> Void) {
        
        let store = CNContactStore()
        
        // Permission 획득
        store.requestAccess(for: .contacts) { (granted, error) in
            guard granted else {
                completion(false)
                return
            }
            
            if self.getContactsMatchingPhoneNumber(phone) {
            
                let contact: CNMutableContact = self.getNewContact(name, phone, email, dept, ext)
                
                let request = CNSaveRequest()
                request.add(contact, toContainerWithIdentifier: nil)
                
                do {
                    try store.execute(request)
                    completion(true)
                } catch {
                
                    completion(false)
                }
            } else {
                completion(false)
            }
        }
    }
        // 새로 등록할 주소록 생성
    private func getNewContact(_ m_name: String, _ m_phone: String, _ m_email: String, _ m_dept: String, _ m_ext: String) -> CNMutableContact {
        let contact = CNMutableContact()
        contact.givenName = m_name
        
        let phone = CNLabeledValue(label:CNLabelPhoneNumberMobile,
                                   value:CNPhoneNumber(stringValue:m_phone))
        let workLabel = "직장"
        let tel = CNLabeledValue(label:workLabel,
                                 value:CNPhoneNumber(stringValue:m_ext))
        contact.phoneNumbers = [phone, tel]
        
        contact.emailAddresses = [CNLabeledValue(label:CNLabelWork, value:m_email as NSString)]
        contact.organizationName = m_dept
    
        
        
        return contact
    }
    
    func getContactsMatchingPhoneNumber(_ phone: String) -> Bool {
        var result = true
        
        let store = CNContactStore()
        let keysToFetch: [CNKeyDescriptor] = [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor]
    
            
        do {
            let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)
            try store.enumerateContacts(with: fetchRequest) { contact, _ in
                
                for phoneNumber in contact.phoneNumbers {
                    
                    
                    let label = phoneNumber.label ?? "Phone"
                    let value = phoneNumber.value.stringValue
                    
                    if value == phone {
                        print("Name: \(contact.givenName) \(contact.familyName)")
                        print("\(label): \(value )")
                        result = false
                    }
                }
            }
        } catch {
            print("Error fetching contacts: \(error)")
        }
        
        return result
    }
}
