//
//  AppDelegate.swift
//  RichPushNotification
//
//  Created by William.Weng on 2022/6/5.
//

import UIKit
import WWPrint
import WWLog

@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
    
    let CategoryId: String = "MyCategory"
    
    var window: UIWindow?
    var pushToken: String?
    var userInfo: [AnyHashable: Any]?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        initSetting(application, launchOptions: launchOptions)
        return true
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        pushToken = deviceToken._hexString()
    }
}

// MARK: - UNUserNotificationCenterDelegate
extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        var options: UNNotificationPresentationOptions = [.sound, .list, .badge, .banner]
        self.userInfo = notification.request.content.userInfo
        
        guard let triggerType = Constant.NotificationTriggerType.parse(with: notification) else { return }
        
        switch triggerType {
        case .push: options = [.sound]; localNotification()
        case .location: break
        case .timeInterval: break
        case .calendar: break
        }
        
        WWLog.shared.log(self.userInfo?._jsonData()?._string())
        completionHandler(options)
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        self.userInfo = response.notification.request.content.userInfo
        completionHandler()
    }
}

// MARK: - 推播相關
extension AppDelegate {
    
    /// https://www.jianshu.com/p/26b96b991eaf
    /// [初始化設定](https://onevcat.com/2016/08/notification/)
    /// - Parameters:
    ///   - application: [UIApplication](https://www.avanderlee.com/swift/rich-notifications/)
    ///   - launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    func initSetting(_ application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        
        Utility.shared.userNotificationSetting(delegate: self) {
            wwPrint("Granted")
        } rejectedHandler: {
            wwPrint("Reject")
        } result: { (status) in
            wwPrint(status.rawValue)
        }
        
        self.userInfo = application.remoteNotificationUserInfo(launchOptions: launchOptions)
        self.notificationCategorySetting(identifier: CategoryId)
    }
    
    /// [註冊Notification Content Extension => Category](https://www.appcoda.com.tw/user-notifications-ios12/)
    /// - Parameter identifier: [String](https://www.appcoda.com.tw/push-notification/)
    func notificationCategorySetting(identifier: String) {
        let category = UNNotificationCategory(identifier: identifier, actions: [], intentIdentifiers: [])
        UNUserNotificationCenter.current().setNotificationCategories([category])
    }
    
    /// [使用本地通知](https://franksios.medium.com/ios-本地通知-local-notification-b25229f279ec)
    func localNotification() {
        
        let imageURL = Bundle.main.url(forResource: "ダイ", withExtension: "png")
        let attachment = try! UNNotificationAttachment(identifier: "", url: imageURL!, options: nil)
        let content = UNMutableNotificationContent()
        let trigger  =  UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
        
        content.title = "DRAGON QUESTドラゴンクエスト - ダイの大冒険-"
        content.subtitle = "勇者鬥惡龍 達伊的大冒險"
        content.body = "（日語：DRAGON QUESTドラゴンクエスト - ダイの大冒険-）是採用遊戲《勇者鬥惡龍系列》之世界觀創作的日本漫畫作品，由三條陸負責原作，稻田浩司負責作畫。於集英社漫畫雜誌《週刊少年JUMP》1989年第45號至1996年第52號期間進行連載。單行本全37卷。系列漫畫的單行本累計發行量超過4700萬本。"
        content.badge = 1
        content.sound = .default
        content.attachments = [attachment]
        
        let request = UNNotificationRequest(identifier: "notification", content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error { wwPrint(error); return }
            wwPrint("Success")
        }
    }
}
