//
//  ContactModuleModel.swift
//  PhoneManager
//
//  Created by edy on 2025/4/18.
//

import Foundation
import Contacts

struct ContactModel : Codable,Equatable {
    // 联系人名字
    var fullName: String
    
    var givenName : String
    
    var familyName : String
    
    // 联系人电话
    var phoneNumber : [String]?
    
    // 唯一id
    var identifier : String
    
    init(from decoder: any Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.fullName = try container.decode(String.self, forKey: .fullName)
        self.givenName = try container.decode(String.self, forKey: .givenName)
        self.familyName = try container.decode(String.self, forKey: .familyName)
        self.phoneNumber = try container.decodeIfPresent([String].self, forKey: .phoneNumber)
        self.identifier = try container.decode(String.self, forKey: .identifier)
    }
    
}
extension ContactModel {
    init?(contact: CNContact) {
        let fullName = "\(contact.givenName) \(contact.familyName)".trimmingCharacters(in: .whitespaces)
        let givenName = "\(contact.givenName)".trimmingCharacters(in: .whitespaces)
        let familyName = "\(contact.familyName)".trimmingCharacters(in: .whitespaces)
        let phoneNumbers = contact.phoneNumbers.map { $0.value.stringValue }
        let uniqueID = contact.identifier
        if uniqueID.isEmpty {
            return nil
        }
        self.fullName = fullName
        self.givenName = givenName
        self.familyName = familyName
        self.phoneNumber = phoneNumbers
        self.identifier = uniqueID
    }
}

struct ContactModuleModel {
    
    
    var duplicates: [[ContactModel]] = []
    
    var incompleteContacts: [ContactModel] = []
    
    var backups: [BackupInfoModel] = []
    
    var allContacts: [ContactModel] = []
    
    init(duplicates: [[ContactModel]], incompleteContacts: [ContactModel], backups: [BackupInfoModel], allContacts: [ContactModel]) {
        self.duplicates = duplicates
        self.incompleteContacts = incompleteContacts
        self.backups = backups
        self.allContacts = allContacts
    }
}


struct ModuleDataModel {
    
    var titleText :  String
    var subTitleText :  String
    init(titleText: String, subTitleText: String) {
        self.titleText = titleText
        self.subTitleText = subTitleText
    }
}

