import UIKit

extension UIImage {
    func cropToSquare() -> UIImage? {
        let size = min(self.size.width, self.size.height)
        UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), true, 1.0)
        defer { UIGraphicsEndImageContext() }
        self.draw(in: CGRect(x: (size - self.size.width) / 2.0,
                             y: (size - self.size.height) / 2.0,
                             width: self.size.width,
                             height: self.size.height))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

extension UIActivityViewController {
    static func shareSheet(url: URL) {
        let activityView = UIActivityViewController(activityItems: [url], applicationActivities: nil)

        let allScenes = UIApplication.shared.connectedScenes
        let scene = allScenes.first { $0.activationState == .foregroundActive }

        if let windowScene = scene as? UIWindowScene {
            let window: UIWindow?
            if #available(iOS 15.0, *) {
                window = windowScene.keyWindow
            } else {
                window = windowScene.windows.first
            }
            
            if let window = window {
                window.rootViewController?.present(activityView, animated: true, completion: nil)
            }
        }
    }
}
