//
//  FlutterMethodChannels.swift
//  Runner
//
//  Created by FancyLou on 2022/8/31.
//

import Foundation
import Cocoa
import FlutterMacOS
import UserNotifications

class FlutterMethodChannels : NSObject {
    
    let flutterChannelName = "pulgin.pc.o2oa.net/notify"
    let cmdNameNotify = "sendNotify"
    let notifyIdentifier = "net.o2oa.app.flutter.macos"
    let notifyRequestIdentifier = "o2oaNotifyId"

    weak var binaryMessager : FlutterBinaryMessenger?
    var methodChannel : FlutterMethodChannel?
    
    func register(withBinaryMessager bm: FlutterBinaryMessenger) {
        binaryMessager = bm
        // create a method channel
        methodChannel = FlutterMethodChannel.init(name: flutterChannelName, binaryMessenger: binaryMessager!)
        methodChannel?.setMethodCallHandler(self.methodInvoked(call:result:))
    }
    
    private func methodInvoked(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void {
        NSLog(call.method);
        switch(call.method) {
        case cmdNameNotify:
            let dict = call.arguments as! Dictionary<String, String>;
            sendNotify(msgId:  dict["msgId"], title: dict["title"], msgBody: dict["msgBody"])
            result(true) // 返回给flutter
            break;
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    
    private func sendNotify(msgId: String?, title: String?, msgBody: String?) {
        NSLog("发送通知 \(msgId ?? "") \(title ?? "") \(msgBody ?? "")")
        if title == nil || title?.isEmpty == true {
            NSLog("title为空 不发送消息")
            return
        }
        if msgBody == nil || msgBody?.isEmpty == true {
            NSLog("msgBody为空 不发送消息")
            return
        }
        let content = UNMutableNotificationContent()
       content.title = "聊聊消息"
       content.body = "\(title ?? "") : \(msgBody ?? "")"
//       content.userInfo = ["method": "new"] // 用户自定义属性
       content.sound = UNNotificationSound.default
       content.categoryIdentifier = notifyIdentifier
        content.badge = 1
//
        // 操作按钮
//       let testCategory = UNNotificationCategory(identifier: notifyIdentifier,
//                                                 actions: [],
//                                                 intentIdentifiers: [],
//                                                 hiddenPreviewsBodyPlaceholder: "",
//                                                 options: .hiddenPreviewsShowSubtitle)

       let request = UNNotificationRequest(identifier: msgId ?? notifyRequestIdentifier,
                                           content: content,
                                           trigger: nil)

       // Schedule the request with the system.
       let notificationCenter = UNUserNotificationCenter.current()
       notificationCenter.delegate = self
//       notificationCenter.setNotificationCategories([testCategory])
       notificationCenter.add(request) { (error) in
           if error != nil {
               NSLog(error?.localizedDescription ?? "")
           }
       }
        NSLog("发送消息完成。。。。。。。。。。。。。。。。")
    }
    
    // 打开窗口
    @objc private func activateWindow() {
        DispatchQueue.main.async {
            NSApp.windows.first?.orderFrontRegardless()
            NSApp.activate(ignoringOtherApps: true)
        }
        NSLog("打开窗口")
   }
}

extension FlutterMethodChannels: UNUserNotificationCenterDelegate {
    // 用户点击消息处理
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//        NSLog("userNotificationCenter。。。。。。didReceive。。用户点击消息 ?????")
        activateWindow()
//        response.actionIdentifier // 操作按钮点击处理
        completionHandler()
    }
    // 发起通知 声音 弹窗
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.sound, .alert])
    }
}
 
