//
//  TSContactsTool.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/4.
//

import Contacts
import ContactsUI
class TSContactsTool : NSObject, CNContactPickerDelegate{
    weak var targetVC:UIViewController?
    var complate:((Any?,Error?)->Void)?
    private var avatarImage:UIImage?
    
    init(targetVC: UIViewController) {
        self.targetVC = targetVC
    }
    func checkContactsPermission(completion: @escaping (Bool) -> Void) {
        let contactStore = CNContactStore()
        
        switch CNContactStore.authorizationStatus(for: .contacts) {
        case .notDetermined:
            // 用户尚未决定权限，发起请求
            contactStore.requestAccess(for: .contacts) { (granted, error) in
                if granted {
                    completion(true)
                } else {
                    if let error = error {
                        dePrint("请求访问通讯录时出错: \(error.localizedDescription)")
                    }
                    completion(false)
                }
            }
        case .authorized:
            // 已经授权
            completion(true)
        case .denied:
            // 被拒绝
            completion(false)
        case .restricted:
            // 由于家长控制等原因被限制
            completion(false)
        case .limited:
            completion(true)
        @unknown default:
            //"未知权限状态"
            completion(false)
        }
    }
    
    func setContactsAvatar(avatarImage:UIImage,complate:((Any?,Error?)->Void)?){
        self.complate = complate
        checkContactsPermission { isAllow in
            DispatchQueue.main.async {
                if isAllow {
                    self.avatarImage = avatarImage
                    let contactPicker = CNContactPickerViewController()
                     contactPicker.delegate = self
                    self.targetVC?.present(contactPicker, animated: true, completion: nil)
                }else{
                    
                    let ac = UIAlertController(title: nil,
                                               message: "Allow \"Contacts\" permission to set contact photo".localized, preferredStyle: .alert)
                    ac.addAction(UIAlertAction(title: "Cancel".localized, style: .cancel))
                    ac.addAction(UIAlertAction(title: "Setting".localized, style: .default, handler: { _ in
                        if let url = URL(string: UIApplication.openSettingsURLString),
                           UIApplication.shared.canOpenURL(url) {
                            UIApplication.shared.open(url)
                        }
                    }))
                    self.targetVC?.present(ac, animated: true)
                }
            }
        }
    }
    
    // 用户选择联系人后的回调方法
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        // 更新界面显示选中的联系人
        // 设置联系人头像
        setContactAvatar(contact) { error in
            complate?(nil,error)
        }
    }

    
    // 设置选中联系人的头像
    private func setContactAvatar(_ contact: CNContact, callBack:(Error?)->Void) {
           
        guard let photo = avatarImage else {
            callBack(NSError(domain: "avatarImage nil", code: 0))
            return
        }

        // 创建可变的联系人对象
        guard let mutableContact = contact.mutableCopy() as? CNMutableContact else {
            callBack(NSError(domain: "avatarImage nil", code: 0))
            return
        }
 
       // 加载图片并转换为 Data
       if let imageData = photo.jpegData(compressionQuality: 0.5) {
           mutableContact.imageData = imageData
       }
       
       // 创建保存请求
       let contactStore = CNContactStore()
       let saveRequest = CNSaveRequest()
       saveRequest.update(mutableContact)
       do {
           // 执行保存请求
           try contactStore.execute(saveRequest)
           dePrint("Avatar updated successfully")
           callBack(nil)
       } catch {
           dePrint("Error updating contact: \(error)")
           callBack(error)
       }
    }
}


