//
//  BackupViewModel.swift
//  PhoneManager
//
//  Created by 赵前 on 2025/4/20.
//

import Foundation
import Contacts

struct BackupInfoModel:Codable {
    let backupTime: Date
    private(set) var contactCount: Int
    let contacts: [ContactModel]
    
    // 初始化方法
    init(backupTime: Date = Date(), contacts: [ContactModel]) {
        self.backupTime = backupTime
        self.contactCount = contacts.count
        self.contacts = contacts
    }
    
    // 手动实现 Decodable 协议的 init(from:) 方法
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" // 与 ISO8601 格式匹配
        if let backupTimeString = try? container.decode(String.self, forKey:.backupTime),
           let backupTime = dateFormatter.date(from: backupTimeString) {
            self.backupTime = backupTime
        } else {
            self.backupTime = try container.decode(Date.self, forKey:.backupTime)
        }
        self.contacts = try container.decode([ContactModel].self, forKey:.contacts)
        self.contactCount = contacts.count
    }
    
    private enum CodingKeys: String, CodingKey {
        case backupTime
        case contactCount
        case contacts
    }
    
}

class BackupViewModel {
    
    // 备份部分联系人到沙盒
    func backupPartialContacts(_ customContacts: [ContactModel], completion: @escaping (Bool, Error?) -> Void) {
        let newBackupInfo = BackupInfoModel(contacts: customContacts)
        
        guard let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in:.userDomainMask).first else {
            completion(false, NSError(domain: "ContactBackupError", code: 1, userInfo: [NSLocalizedDescriptionKey: "无法获取沙盒目录"]))
            return
        }
        let backupFileURL = documentsDirectory.appendingPathComponent("partial_contacts_backup.json")
        
        var existingBackups: [BackupInfoModel] = []
        if let data = try? Data(contentsOf: backupFileURL) {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601
            do {
                existingBackups = try decoder.decode([BackupInfoModel].self, from: data)
            } catch {
                print("Failed to decode existing backups: \(error)")
            }
        }
        
        existingBackups.append(newBackupInfo)
        
        do {
            let encoder = JSONEncoder()
            encoder.dateEncodingStrategy = .iso8601
            let jsonData = try encoder.encode(existingBackups)
            try jsonData.write(to: backupFileURL)
            completion(true, nil)
        } catch {
            completion(false, error)
        }
    }
    
    // 备份所有联系人到沙盒
    func backupAllContacts(_ customContacts: [ContactModel], completion: @escaping (Bool, Error?) -> Void) {
        backupPartialContacts(customContacts) { success, error in
            completion(success, error)
        }
    }
    
    // 从沙盒中取出联系人并转换为自定义模型
    func retrieveContactsFromBackup(completion: @escaping ([BackupInfoModel]?, Error?) -> Void) {
        guard let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in:.userDomainMask).first else {
            completion(nil, NSError(domain: "ContactBackupError", code: 1, userInfo: [NSLocalizedDescriptionKey: "无法获取沙盒目录"]))
            return
        }
        let backupFileURL = documentsDirectory.appendingPathComponent("partial_contacts_backup.json")
        do {
            let jsonData = try Data(contentsOf: backupFileURL)
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601
            // 尝试解码为 BackupInfoModel 数组
            let backupInfos = try decoder.decode([BackupInfoModel].self, from: jsonData)
            // 根据时间倒序下
            let sortedModels = backupInfos.sorted { $0.backupTime > $1.backupTime }
            completion(sortedModels, nil)
        } catch {
            Print(error.localizedDescription)
            completion(nil, error)
        }
    }
    
    func saveModel(model:[BackupInfoModel],completion: @escaping (Bool, Error?) -> Void){
        guard let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in:.userDomainMask).first else {
            completion(false, NSError(domain: "ContactBackupError", code: 1, userInfo: [NSLocalizedDescriptionKey: "无法获取沙盒目录"]))
            return
        }
        let backupFileURL = documentsDirectory.appendingPathComponent("partial_contacts_backup.json")
        do {
            let encoder = JSONEncoder()
            encoder.dateEncodingStrategy = .iso8601
            let jsonData = try encoder.encode(model)
            try jsonData.write(to: backupFileURL)
            completion(true, nil)
        } catch {
            completion(false, error)
        }
    }
    
}
