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

import UIKit

// MARK: - AppDelegate (class function)
extension UIApplication {
    
    /// [取得由推播打開APP的userInfo](https://developerhowto.com/2018/12/07/implement-push-notifications-in-ios-with-swift/)
    /// [application(_:didFinishLaunchingWithOptions:)](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622921-application)
    /// - Parameter launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    /// - Returns: [AnyHashable : Any]?
    func remoteNotificationUserInfo(launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> [AnyHashable : Any]? {
        
        guard let remoteNotification = launchOptions?[.remoteNotification],
              let userInfo = remoteNotification as? [AnyHashable : Any]
        else {
            return nil
        }
        
        return userInfo
    }
}

// MARK: - JSONSerialization
extension JSONSerialization {
    
    /// [JSONObject => JSON Data](https://medium.com/彼得潘的-swift-ios-app-開發問題解答集/利用-jsonserialization-印出美美縮排的-json-308c93b51643)
    /// - ["name":"William"] => {"name":"William"} => 7b226e616d65223a2257696c6c69616d227d
    /// - Parameters:
    ///   - object: Any
    ///   - options: JSONSerialization.WritingOptions
    /// - Returns: Data?
    static func _data(with object: Any, options: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions()) -> Data? {
        
        guard JSONSerialization.isValidJSONObject(object),
              let data = try? JSONSerialization.data(withJSONObject: object, options: options)
        else {
            return nil
        }
        
        return data
    }
}

// MARK: - Dictionary (class function)
extension Dictionary {
    
    /// Dictionary => JSON Data
    /// - ["name":"William"] => {"name":"William"} => 7b226e616d65223a2257696c6c69616d227d
    /// - Returns: Data?
    func _jsonData(options: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions()) -> Data? {
        return JSONSerialization._data(with: self, options: options)
    }
}

// MARK: - Data (class function)
extension Data {
    
    /// Data => 16進位文字
    /// - %02x - 推播Token常用
    /// - Returns: String
    func _hexString() -> String {
        let hexString = reduce("") { return $0 + String(format: "%02x", $1) }
        return hexString
    }
    
    /// Data => 字串
    /// - Parameter encoding: 字元編碼
    /// - Returns: String?
    func _string(using encoding: String.Encoding = .utf8) -> String? {
        return String(bytes: self, encoding: encoding)
    }
}

