import cv2
from edge_engine.common.logsetup import logger
from edge_engine.ai.model.modelwraper import ModelWrapper
import json
# from scripts.utils.openvino_utils import OpenVinoDetector
from scripts.utils.infocenter import InfoCenter
import time


class PeopleMonitor(ModelWrapper):
    def __init__(self, config, pubs, device_id):
        super().__init__()
        self.config = config['config']
        self.type = config['inputConf']['sourceType']
        if config['inputConf']['sourceType'] == 'videofile':
            f = open('test3.json', "r")
            self.dets = json.loads(f.read())
            f.close()
        self.rtp = pubs.rtp_write
        self.ic = InfoCenter(device_id=device_id)
        # self.ov = OpenVinoDetector(model_detector_pth="assets/person-detection-retail-0013.xml",
        #                            model_bin="assets/person-detection-retail-0013.bin",
        #                            confidence=0.5)
        self.acknowledge_no_people = False
        self.old_detection = "Sample"

    def _pre_process(self, x):
        """
        Do preprocessing here, if any
        :param x: payload
        :return: payload
        """
        return x

    def _post_process(self, x):
        """
        Apply post processing here, if any
        :param x: payload
        :return: payload
        """
        self.rtp.publish(x)
        return x

    def _predict(self, x):
        """Implement core mask_model inference code here"""
        try:
            time.sleep(0.05)
            frame = x['frame']
            f_copy = frame.copy()
            frameId = x['frameId']
            if self.type == 'videofile':
                detections, frames = self.dets[int(frameId)][str(frameId)]['detections'], frame
            else:
                detections, frames = self.ov.person_detector(frame)

            # for det in detections:
            #     cv2.rectangle(f_copy, (det[1], det[0]), (det[3], det[2]), (255, 0, 0), 2)
            if str(detections) != str(self.old_detection):
                logger.warn("Number Detected as {}".format(detections))
                self.ic.send_payload(frame=f_copy,
                                     person_count=0,
                                     message=str(detections),
                                     alert_sound="sound_1")
                self.old_detection = str(detections)

            x['frame'] = cv2.resize(f_copy, (self.config.get('FRAME_WIDTH'), self.config.get('FRAME_HEIGHT')))
            return x
        except Exception as e:
            logger.error(f"Error: {e}", exc_info=True)
            x['frame'] = cv2.resize(x['frame'], (self.config.get('FRAME_WIDTH'), self.config.get('FRAME_HEIGHT')))
            return x
