//
//  Swizzler.swift
//  Duckable
//
//  Created by Shadowfacts on 11/7/22.
//

import UIKit
import os.log

private var hasInitialized = false
var isDetentChangingDueToGrabberAction = false

@available(iOS 16.0, *)
func swizzleSheetController() {
    guard !hasInitialized else {
        return
    }
    hasInitialized = true
    
    var originalIMP: IMP?
    let imp = imp_implementationWithBlock({ (self: UISheetPresentationController, param: AnyObject) in
        let original = unsafeBitCast(originalIMP!, to: (@convention(c) (UISheetPresentationController, AnyObject) -> Void).self)
        isDetentChangingDueToGrabberAction = true
        original(self, param)
        isDetentChangingDueToGrabberAction = false
    } as @convention(block) (UISheetPresentationController, AnyObject) -> Void)
    let sel = [":", "PrimaryAction", "GrabberDidTrigger", "dropShadowView", "_"].reversed().joined()
    originalIMP = class_replaceMethod(UISheetPresentationController.self, Selector(sel), imp, "v@:@")
    if originalIMP == nil {
        os_log(.fault, log: .default, "Unable to initialize Duckable grabber tap hook")
    }
}
