//
//  AppDelegate.swift
//  AcaMate
//
//  Created by Sean Kim on 11/26/24.
//

import SwiftUI
import UIKit
import UserNotifications

import KakaoSDKCommon
import KakaoSDKAuth

import FirebaseCore



class AppDelegate: NSObject, UIApplicationDelegate {
    
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        printLog("Start Set AppDelegate")
        
        if let kakaoAppKey = KEY.loadKey(for: "kakaoAppKey") {
            printLog("KAKAO APP KEY : \(kakaoAppKey)")
            KakaoSDK.initSDK(appKey: kakaoAppKey)
        }
        
        //MARK: - Set Notification
        
        let center = UNUserNotificationCenter.current()
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        center.requestAuthorization(options: authOptions) { granted, error in
            if let error = error {
                printLog("인증 오류: \(error.localizedDescription)")
            }
            if granted {
                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            } else {
                printLog("알람 권한 해제.")
            }
        }
        center.delegate = self
        
        //MARK: - 네트워크 모니터 초기화
        _ = NetworkMonitor.shared
        
        //MARK: - FIREBASE 초기화
        FirebaseApp.configure()
        
        printLog("End Set AppDelegate")
        return true
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
//        if (AuthApi.isKakaoTalkLoginUrl(url)) {
//            return AuthController.handleOpenUrl(url: url)
//        }
//
        return false
    }
    
    
    
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    //
    func registerForRemoteNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            print("Permission granted: \(granted)")
            if let error = error {
                printLog("권한 요청 실패 \(error)")
            }
            printLog("권한 : \(granted)")
        }

        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
    
    // 디바이스 토큰 등록 성공 시
    func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02.2hX", $1)})
        printLog("APNs 디바이스 토큰: \(deviceTokenString)")
        // 서버로 디바이스 토큰 전달 로직 추가
    }
    
    // 디바이스 토큰 등록 실패 시
    func application(_ application: UIApplication,didFailToRegisterForRemoteNotificationsWithError error: Error) {
        printLog("APNs 등록 실패: \(error)")
    }
    
    // 앱 켜져있을때 알럿 받으면 직접 로컬로 알림 띄워주는 곳
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
        let userInfo = notification.request.content.userInfo
        
        if let apsData = userInfo["aps"] as? [AnyHashable: Any],
           let badge = apsData["badge"] as? Int {
            printLog("\(apsData)")
            do {
                try await UNUserNotificationCenter.current().setBadgeCount(badge)
            } catch {
                //오류
            }
        }
        
        if #available(iOS 14.0, *) {
            return [[.list,.banner,.sound]]
        } else {
            return[[.alert,.sound]]
        }
    }
    
    // 수신 받은 Noti를 터치해 앱으로 진입했을 때 호출 (앱 상태 여부 무관)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        if let apsData = userInfo["aps"] as? [AnyHashable: Any] {
            if let alert = apsData["alert"] as? [AnyHashable: Any] {
                printLog("apsData: \(apsData)")
                printLog("alert: \(alert)")
                if let param = alert["parameter"] {
                    printLog(param as? String)
                }
            }
        }
    }
}
