//
//  NotificationService.swift
//  BeautifulIndonesiaNotificationService
//
//  Created by Akhmad Al Qindi Irsyam on 01/03/23.
//

import UserNotifications
import Intents
import UIKit

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        guard let bestAttemptContent = bestAttemptContent else {
            return
        }
        
        // Check if the notification is a communication notification
        let categoryIdentifier = bestAttemptContent.categoryIdentifier
        if categoryIdentifier != "chat" {
            contentHandler(bestAttemptContent)
            return
        }
        
        let avatarDefault = INImage(imageData: UIImage(systemName: "person.circle.fill")!.withTintColor(.gray).pngData()!)
        var sender = INPerson(personHandle: INPersonHandle(value: "02cdfdfdac", type: .unknown), nameComponents: nil, displayName: "Meme", image: avatarDefault, contactIdentifier: "02cdfdfdac", customIdentifier: "02cdfdfdac")
        
//        sender = INPerson(personHandle: INPersonHandle(value: "02cdfdfdac", type: .unknown), nameComponents: nil, displayName: "Meme", image: INImage(url: URL(string: "https://i.pinimg.com/474x/69/77/b7/6977b70a129ec184527433bbdf9fe457.jpg")!), contactIdentifier: "02cdfdfdac", customIdentifier: nil)
        
//        let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
//        let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
//        let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
//        if let dirPath = paths.first {
//            let fileURL = URL(fileURLWithPath: dirPath).appendingPathComponent("6977b70a129ec184527433bbdf9fe457.jpg")
//            if FileManager.default.fileExists(atPath: fileURL.path) {
//                sender = INPerson(personHandle: INPersonHandle(value: "02cdfdfdac", type: .unknown), nameComponents: nil, displayName: "Hansen", image: INImage(url: ), contactIdentifier: "02cdfdfdac", customIdentifier: nil)
//            }
//        }

        let incomingMessageIntent = INSendMessageIntent(recipients: [sender], outgoingMessageType: .outgoingMessageText, content: nil, speakableGroupName: INSpeakableString(spokenPhrase: "Test Group"), conversationIdentifier: "Test Group", serviceName: nil, sender: sender, attachments: nil)
        incomingMessageIntent.setImage(avatarDefault, forParameterNamed: \.speakableGroupName)

        let interaction = INInteraction(intent: incomingMessageIntent, response: nil)
        interaction.direction = .incoming
        interaction.donate { error in
            if let error = error {
                contentHandler(bestAttemptContent)
                return
            }
            
            let content = UNMutableNotificationContent()
            content.subtitle = "testing subTitle"
            content.body = "testing body"
            content.sound = .default
            let myRequest = UNNotificationRequest(identifier: "02cdfdfdac", content: content, trigger: nil)
            let myContent = myRequest.content

            do {
                // Update notification content before displaying the
                // communication notification.
                if #available(iOSApplicationExtension 15.0, *) {
                    let updatedContent = try myContent.updating(from: incomingMessageIntent)
                    contentHandler(updatedContent)
                } else {
                    contentHandler(bestAttemptContent)
                }

            } catch {
                contentHandler(bestAttemptContent)
            }
        }
    }

}
