import UserNotifications

class NotificationManager {
   
   class func requestPermission() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if granted {
                print("通知权限已获取")
                self.scheduleDailyNotification()
            } else if let error = error {
                print("通知权限错误: \(error.localizedDescription)")
            }
        }
    }
    
    class func scheduleDailyNotification() {
        self.cancelAllNotifications()
        let date = SpeakElePublicManager.share.PublicData.MPractice.date() ?? Date()
        let calendar = Calendar(identifier: .gregorian)
        let dateComponents = calendar.dateComponents([.hour,.minute], from: date)
        
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
        
        // 创建通知内容
        let content = UNMutableNotificationContent()
        content.title = ""
        if SpeakElePublicManager.share.userInfo.targetLanguage?.contains("English") ?? true {
            content.body = "Hi there! Welcome to the chat-feel free to ask me anything, and I'll help however I can!"
        }else{
            content.body = " ¡Hola! Bienvenido al chat, no dudes en preguntar me cualquier cosa, y ayudaré de cualquier manera que pueda!"
        }
        content.sound = .default
        
        let request = UNNotificationRequest(
            identifier: "dailyReminder",
            content: content,
            trigger: trigger
        )
        
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                Print("添加通知失败: \(error.localizedDescription)")
            } else {
                Print("每日下午\(SpeakElePublicManager.share.PublicData.MPractice)通知已设置")
            }
        }
    }
    
    // 取消所有通知
    class func cancelAllNotifications() {
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    }
}    
