//
//  AppDelegate.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 12/07/2024.
//

import Foundation
import UIKit
import LeStorage
import UserNotifications

class AppDelegate : NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        UIApplication.shared.registerForRemoteNotifications()
        UNUserNotificationCenter.current().delegate = self

        Logger.log("didFinishLaunchingWithOptions")
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        if StoreCenter.main.hasToken() {
            Task {
                do {
                    let services = try StoreCenter.main.service()
                    try await services.postDeviceToken(deviceToken: deviceToken)
                } catch {
                    Logger.error(error)
                }
            }
        }
//        Logger.log("token = \(deviceToken)")
    }
    
    func application(_ application: UIApplication,
                     didFailToRegisterForRemoteNotificationsWithError
                     error: Error) {
        Logger.error(error)
    }
    
    // MARK: - UNUserNotificationCenterDelegate

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // Show the notification as a banner even when the app is in the foreground
        completionHandler([.banner, .sound, .badge])
    }

    // Handle notifications when the user taps on them
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Handle the notification content here
        print("User Info: \(userInfo)")

        // Perform your custom actions based on the notification content
        completionHandler()
    }
    
    static func askPermissions() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { success, error in
            print("requestAuthorization > success = \(success), error = \(String(describing: error))")
        }
    }

}
