//
//  SaveToPhotosActivity.swift
//  Tusker
//
//  Created by Shadowfacts on 1/2/23.
//  Copyright © 2023 Shadowfacts. All rights reserved.
//

import UIKit
import UniformTypeIdentifiers
import Photos

class SaveToPhotosActivity: UIActivity {
    
    override class var activityCategory: UIActivity.Category {
        return .action
    }
    override var activityType: UIActivity.ActivityType? {
        return .saveToPhotos
    }
    
    override var activityTitle: String? {
        return "Save to Photos"
    }
    override var activityImage: UIImage? {
        UIImage(systemName: "square.and.arrow.down")
    }
    
    override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
        return activityItems.contains(where: {
            if let url = $0 as? URL,
               let type = UTType(filenameExtension: url.pathExtension){
                return type.conforms(to: .movie) || type.conforms(to: .video) || type.conforms(to: .image)
            } else {
                return false
            }
        })
    }
    
    private var url: URL?
    private var type: UTType?
    
    override func prepare(withActivityItems activityItems: [Any]) {
        for case let url as URL in activityItems {
            self.url = url
            type = UTType(filenameExtension: url.pathExtension)!
        }
    }
    
    override func perform() {
        guard let url,
              let type else {
                return
            }
        PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in
            guard case .authorized = status else {
                return
            }
            PHPhotoLibrary.shared().performChanges {
                if type.conforms(to: .movie) || type.conforms(to: .video) {
                    _ = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
                } else {
                    _ = PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: url)
                }
            } completionHandler: { _, _ in
                self.activityDidFinish(true)
            }
        }
    }
    
}
