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!")

    # @staticmethod
    def insert_attendance_event_to_mongo(self,data):

        try:
            mongo_1 = MongoLogger()
            input_data = {
                "eventId": str(uuid1()).split('-')[0],
                "cameraId": data['deviceId'],
                "cameraName": mongo_1.camera_mapping_json.get(data['deviceId'], "Thermal Camera"),
                "timestamp": datetime.now(),
                "frame": " ",
                "eventtype": "Activity Recognition",
                "bg_color": "#474520",
                "font_color": "#FFF00",
                "intrusion_message": "ACC SURAKSHA PP< MRP : YES",
                "alert_sound": " ",
                "logged_activity": "Cement bag detected ",
                "mrp_frmae": " ",
                "mrp_roi": " ",
                "app": "cement"
                # "sequence_start_text": data["sequence_start_text"],
                # "picking_text": data["picking_text"],
                # "non_needle_text": data["non_needle_text"],
                # "needle_text": data["needle_text"],
                # "passing_text": data["passing_text"],
                # "sequence_count_text": data["sequence_count_text"],
                # "stoppage_text": data["stoppage_text"],
                # "sequence_end_text": data["sequence_end_text"]
            }
            if os.environ.get('app') is not None:
                input_data['app'] = os.environ.get('app')

            logger.info("Pushing to Mongo..")
            mongo_1.attendance_event_collection.insert_one(input_data)
            mongo_1.update_count_api()
        except Exception as e:
            logger.exception(e)
