import traceback
from datetime import datetime
from uuid import uuid1
from pymongo import MongoClient
from scripts.common.config import MONGO_DB_OBJ, APP_MONGO_COLLECTION
from edge_engine.common.logsetup import logger


class MongoLogger:
    def __init__(self):
        self.attendance_event_collection = MONGO_DB_OBJ[APP_MONGO_COLLECTION.get('eventLogCollection')]
        self.camera_configuration = MONGO_DB_OBJ[APP_MONGO_COLLECTION.get('cameraConfigurationCollection')]
        self.camera_mapping_json = self.get_all_cameras()

    def get_all_cameras(self):
        camera_mapping_json = self.camera_configuration.find({'decommissioned': False},
                                                                                          {"_id": 0})
        camera_json = {}
        for each in camera_mapping_json:
            camera_json[each['cameraId']] = each['cameraName']
        return camera_json

    def insert_attendance_event_to_mongo(self, data):
        try:
            input_data = {
                "eventId": str(uuid1()).split('-')[0],
                "cameraId": data['deviceId'],
                "cameraName": self.camera_mapping_json.get(data['deviceId'], "Thermal Camera"),
                "timestamp": datetime.now().strftime("%b %d %Y %H:%M:%S"),
                "frame": data['frame'],
                "eventtype": "Intrusion Detection",
                "bg_color": data["bg_color"],
                "font_color": data["font_color"],
                "intrusion_message": data["message"],
                "alert_sound": data["alert_sound"],
                "logged_activity": data["activity"]}
            
            logger.info("Pushing to Mongo..")
            input_data["timestamp"] = datetime.now()
            self.attendance_event_collection.insert(input_data)
        except Exception as e:
            logger.info(e)
            logger.error(traceback.format_exc())
