import os
from datetime import datetime
from requests import post
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():
        asset_id = os.environ.get('asset_id')
        asset_hierarchy = os.environ.get('asset_hierarchy')
        count_update_endpoint = os.environ.get('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),
                            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": "4",
                "cameraName": self.camera_mapping_json.get(data['deviceId'], "Thermal Camera"),
                "timestamp": datetime.now(),
                "frame": data['frame'],
                "eventtype": data["message"],
                "bg_color": data["bg_color"],
                "font_color": data["font_color"],
                "intrusion_message": data["event_type"],
                "alert_sound": data["alert_sound"],
                "logged_activity": data["activity"],
                "frame_id": data["frame_id"]}
            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()
        except Exception as e:
            logger.exception(e)
