import json
import vp_module as vp
from infer_module import yolov11 as yolo


class DetectNode(vp.vp_node):
    def __init__(self, node_name, model_path, callback=None):
        super().__init__(node_name)
        self.initialized()
        self.callback = callback
        self.engin = yolo.create_infer(model_path)

    def __del__(self):
        self.gate_open()
        self.deinitialized()
        self.engin.reset()

    def handle_frame_meta(self, meta):
        meta.any_targets = self.engin.commit(meta.frame)
        if self.callback:
            targets = meta.any_targets.get()
            datas = []
            for target in targets:
                boxs = json.loads(target.json.text)
                for box in boxs:
                    datas.append(box)
            self.callback(None, datas)
        return super().handle_frame_meta(meta)
