//
//  StatusActivityItemSource.swift
//  Tusker
//
//  Created by Shadowfacts on 5/14/20.
//  Copyright © 2020 Shadowfacts. All rights reserved.
//

import UIKit
import LinkPresentation
import SwiftSoup

class StatusActivityItemSource: NSObject, UIActivityItemSource {
    let status: StatusMO
    
    init(_ status: StatusMO) {
        self.status = status
    }
    
    func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
        return status
    }
    
    func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
        return status
    }
    
    func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
        guard #unavailable(iOS 16.4) else {
            // iOS 16.4 shows the full content and attachments in the Messages preview, better than what we can generate with LPLinkMetadata
            return nil
        }
        let metadata = LPLinkMetadata()
        metadata.originalURL = status.url!
        metadata.url = status.url!
        let doc = try! SwiftSoup.parse(status.content)
        let content = try! doc.text()
        metadata.title = "\(status.account.displayName): \"\(content)\""
        if let avatar = status.account.avatar,
           let data = ImageCache.avatars.getData(avatar),
           let image = UIImage(data: data) {
            metadata.iconProvider = NSItemProvider(object: image)
        }
        return metadata
    }
    
    func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
        return "Post by @\(status.account.acct)"
    }

}
