//
//  View+PresentViewController.swift
//  MatchGeom
//
//  Created by Shadowfacts on 4/24/23.
//

import SwiftUI

extension View {
    func presentViewController(_ makeVC: @escaping () -> UIViewController, isPresented: Binding<Bool>) -> some View {
        self
            .background(
                ViewControllerPresenter(makeVC: makeVC, isPresented: isPresented)
            )
    }
}

private struct ViewControllerPresenter: UIViewControllerRepresentable {
    let makeVC: () -> UIViewController
    @Binding var isPresented: Bool
    
    func makeUIViewController(context: Context) -> UIViewController {
        return UIViewController()
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        if isPresented {
            if uiViewController.presentedViewController == nil {
                let presented = makeVC()
                presented.presentationController!.delegate = context.coordinator
                uiViewController.present(presented, animated: true)
                context.coordinator.didPresent = true
            }
        } else {
            if context.coordinator.didPresent,
               let presentedViewController = uiViewController.presentedViewController,
               !presentedViewController.isBeingDismissed {
                uiViewController.dismiss(animated: true)
                context.coordinator.didPresent = false
            }
        }
    }
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(isPresented: $isPresented)
    }
    
    class Coordinator: NSObject, UIAdaptivePresentationControllerDelegate {
        @Binding var isPresented: Bool
        var didPresent = false
        
        init(isPresented: Binding<Bool>) {
            self._isPresented = isPresented
        }
        
        func presentationControllerWillDismiss(_ presentationController: UIPresentationController) {
            isPresented = false
            didPresent = false
        }
    }
}
