import os
from datetime import datetime

# Security changes start
# from requests import post
from scripts.utils.ilens_request_handler import post
# Security changes stop

from uuid import uuid1
from urllib.parse import urljoin
from edge_engine.common.logsetup import logger
from scripts.common.config import MONGO_DB_OBJ, APP_MONGO_COLLECTION


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

    @staticmethod
    def update_count_api(bag_type):
        asset_id = os.environ.get('asset_id')
        asset_hierarchy = os.environ.get('asset_hierarchy')
        count_update_endpoint = os.environ.get('count_update_endpoint')
        logger.debug("count_update_endpoint",count_update_endpoint)
        if asset_id is not None and count_update_endpoint is not None and asset_hierarchy is not None:
            response = post(url=count_update_endpoint,
                            json=dict(asset_hierarchy=asset_hierarchy, count_increment=1, asset_id=asset_id,
                                      bag_type=bag_type), timeout=5)
            if response.status_code != 200:
                logger.warning(
                    "Value not updated in cards!. Invalid response from Update Count API: {}".format(response.content))
        else:
            logger.warning("Either asset_id, asset_hierarchy or count_update_endpoint is not set!."
                           " Not updating the cards API!")

    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(),
                "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"],
                "mrp_frmae": data["mrp_frmae"],
                "mrp_roi": data["mrp_roi"]}
            if os.environ.get('app') is not None:
                input_data['app'] = os.environ.get('app')

            logger.info("Pushing to Mongo..")
            self.attendance_event_collection.insert_one(input_data)
            self.update_count_api(data["bag_type"])
        except Exception as e:
            logger.exception(e)

    def get_camera_details(self, camera_id):
        camera_details_json = self.camera_configuration.find_one({"cameraId": camera_id})
        return camera_details_json
