from common_code.settings import get_logger

from utils import StreamManager, run_model
import multiprocessing as mp
import cv2

logger = get_logger('live_inference',file_path = '/var/log/live_inference.log', stdout=True)

all_cameras_config = {
    "camera_sidefeeder": {
        'url': "rtsp://admin:marybear@192.168.1.157:554/h264Preview_01_sub",
        'resolution': (360, 640, 3)
    },
    "camera_driveway": {
        'url': "rtsp://admin:marybear@192.168.1.152:554/h264Preview_01_sub",
        'resolution': (480, 640, 3)
    },
    "camera_railing": {
        'url': "rtsp://admin:marybear@192.168.1.153:554/h264Preview_01_sub",
        'resolution': (512, 896, 3)
    },
    "camera_ptz": {
        'url': "rtsp://admin:marybear@192.168.1.155:554/h264Preview_01_sub",
        'resolution': (360, 640, 3)
    },
    "camera_wrenwatch": {
        'url': "rtsp://admin:marybear@192.168.1.158:554/h264Preview_01_sub",
        'resolution': (360, 640, 3)
    },
    "camera_backyard": {
        'url': "rtsp://admin:marybear@192.168.1.162:554/h264Preview_01_sub",
        'resolution': (432, 1536, 3),
        'split_into_two': True
    },
}

cameras_config = dict()
k_c = 'camera_railing'
#cameras_config[k_c] = all_cameras_config[k_c]
cameras_config = all_cameras_config


cameras = dict()
from random import random
img_scoring_queue = mp.Queue(maxsize = len(cameras_config)*2)
for cam_name, details in cameras_config.items():
    rtsp_url = details['url']
    if random() < -1:
        rtsp_url = 'rtsp://admin:marybear@192.168.1.124'
        print(f"Switching RTSP stream for {cam_name}")
    resolution = details['resolution']
    cameras[cam_name] = StreamManager(rtsp_url=rtsp_url,
                                      resolution=resolution,
                                      img_scoring_queue=img_scoring_queue,
                                      camera_name=cam_name,
                                      split_into_two=details.get(

                                          'split_into_two', False))
    cameras[cam_name].start_process()
    logger.info(f'Started StreamManager for {cam_name}')

pp = mp.Process(target=run_model, args=(img_scoring_queue, ))
pp.start()
logger.info(f'Started model scoring process')




# %%





iters = 0
while True:
    for cam_name, obj in cameras.items():
        logger.info(f'Asking {cam_name} process to score')
        obj.score_frame_in_queue( save_to_disk = True)
#        obj.score_frame_in_queue( save_to_disk = iters % 10 == 0)
        obj.health_check()
        
    iters+=1

        




# # %%
# from utils import species_list
# import pickle
# import json
# with open('crap.p','rb') as fw:
#     dump = pickle.load(fw)


# camera_name = dump[1]['camera_name']
# timestamp = dump[1]['image_timestamp']
# ff = dump[0]

# has_scores = {idx:x for idx,x in enumerate(dump[0]) if len(x) > 0}

# score_dict = {}

# score_dict['timestamp'] = timestamp.timestamp()
# score_dict['scores'] = list()

# for idx, sc in has_scores.items():
#     for r in sc:
#         score_dict['scores'].append({'idx': idx, 'species': species_list[idx], 'boxes':r[0:4].tolist(), 'score': r[4].tolist()})
        

# def round_floats(obj, decimals=4):
#     if isinstance(obj, float):
#         return round(obj, decimals)
#     elif isinstance(obj, dict):
#         return {k: round_floats(v, decimals) for k, v in obj.items()}
#     elif isinstance(obj, list):
#         return [round_floats(item, decimals) for item in obj]
#     return obj
# json_str = json.dumps(round_floats(score_dict))


# with open('/home/thebears/source/infer/scores/' + camera_name,'a') as ff:
#     ff.write(json_str)
#     ff.write('\n')

# import matplotlib.pyplot as plt
# plt.imshow(dump[1]['frame'])
# plt.show()

# # %%
# for cam_name, cls in cameras.items():
#     ret = cls.capture_image()
#     cv2.imwrite('images/' + cam_name + '.jpg', ret['image'])

