from .scripts import *

def deferred_capture(viewport_window, callback, is_hdr=False, subscription_name=None):
    def _get_subs_name():
        import sys

        frame = sys._getframe(1).f_back
        f_code = frame.f_code

        filepath = f_code.co_filename
        lineno = frame.f_lineno

        return "VP capt %s:%d" % (filepath[-40:], lineno)
    class CaptureHelper:
        def capture_function(self, event):
            self.deferred_capture_subs = None
            if is_hdr:
                viewport_rp_resource = viewport_window.get_drawable_hdr_resource()
            else:
                viewport_rp_resource = viewport_window.get_drawable_ldr_resource()
            callback(viewport_rp_resource)

    if subscription_name is None:
        subscription_name = _get_subs_name()

    capture_helper = CaptureHelper()
    capture_helper.deferred_capture_subs = viewport_window.get_ui_draw_event_stream().create_subscription_to_pop(
        capture_helper.capture_function,
        name=subscription_name
    )
