import os
import datetime
import json
import pytz
import requests
from requests import post
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()
            total_time = data["picking_time"] + data["non_needle_time"] + data["needle_time"] + data["passing_time"]
            # input_data = {"data":
            #   {
            #   "event_code": "EC011",
            #   "event_name": "camera_events",
            #   "event_time":datetime.datetime.now().astimezone(tz=pytz.timezone("Asia/Kolkata")).strftime("%Y-%m-%d %H:%M:%S"),
            #   "event_desc":"Camera event",
            #   "event_severity":"high",
            #   "project_id":"project_099",
            #   "tz": "Asia/Kolkata",
            #   "event_table":"iot_camera",
            #   "event_src_type": "Iot camera event",
            #   "event_data":{
            #     "emp_id":3,
            #     "sequences_list":[
            #       {
            #         "sequence_id":1,
            #         "sequence_name":"picking",
            #         "sequence_duration": data["picking_time"]
            #       },
            #       {
            #         "sequence_id":2,
            #         "sequence_name":"needle",
            #         "sequence_duration": data["needle_time"]
            #       },
            #       {
            #         "sequence_id":3,
            #         "sequence_name":"non_needle",
            #         "sequence_duration": data["non_needle_time"]
            #       },
            #       {
            #         "sequence_id":4,
            #         "sequence_name":"passing",
            #         "sequence_duration": data["passing_time"]
            #       }
            #     ],
            #     "operation_master_id": "K1",
            #     "operation_name": "Kinari",
            #     "station_id":"S1",
            #     "sequence_start_time": data["sequence_start_time"],
            #     "sequence_end_time": data["sequence_end_time"],
            #     "stoppage_count": data["stoppage_count"]
            #   }
            # },"project_id": "project_099"
            # }

            mongo_input_data = {
                "cameraId": "123456",
                "eventId": "43a437c2",
                "eventtype": "Micro Pose Detection",
                "cameraName": "Gokaldas Action Recognition Camera",
                "timestamp": datetime.datetime.now(),
                "logged_by": "svc-ilens",
                "event_description": data["operation_name"],
                "operation_master_id": data["operation_master_id"],
                "operation_name": data["operation_name"],
                "station_id": data["station_id"],
                "emp_id": data["emp_id"],
                "event_data": {
                    "activity_metadata": [
                        {
                            "type": "sequence",
                            "value": {
                                "start_time": data["sequence_start_time"]
                            }
                        },
                        {
                            "type": "stoppage",
                            "value": {
                                "count": data["stoppage_count"]
                            }
                        },
                        {
                            "type": "sequence",
                            "value": {
                                "end_time": data["sequence_end_time"]
                            }
                        },
                        {
                            "type": "cycle",
                            "value": {
                                "id": data["cycle_id"]
                            }
                        }
                    ],
                    "activity_data": [
                        {
                            "type": "sequence",
                            "value": {
                                "picking": data["picking_time"]
                            }
                        },
                        {
                            "type": "sequence",
                            "value": {
                                "needle": data["needle_time"]
                            }
                        },
                        {
                            "type": "sequence",
                            "value": {
                                "non-needle": data["non_needle_time"]
                            }
                        },
                        {
                            "type": "sequence",
                            "value": {
                                "passing": data["passing_time"]
                            }
                        },
                        {
                            "type": "sequence",
                            "value": {
                                "needle_ratio": data["needle_ratio"]
                            }
                        }
                    ]
                },"app":"micropose_detection"
            }


            # request_header = {"username": Secrets.auth_username, "password": Secrets.auth_password}

            # request_header = {"username": "AllGoodNamesRGone", "password": "comBRANSeANtamasEbICaPeC"}
            # request_header = {"username": "AllGoodNamesRGone", "password": "comBRANSeANtamasEbICaPeC"}
         



        # "cameraId": data['deviceId'],
                # "cameraName": mongo_1.camera_mapping_json.get(data['deviceId'], "Thermal Camera"),
                # "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_time": data["sequence_start_time"],
            #     "picking_time": data["picking_time"],
            #     "non_needle_time": data["non_needle_time"],
            #     "needle_time": data["needle_time"],
            #     "passing_time": data["passing_time"],
            #     "cycle_id": data["cycle_id"],
            #     "stoppage_count": data["stoppage_count"],
            #     "sequence_end_time": data["sequence_end_time"],
            # }
            if os.environ.get('app') is not None:
                mongo_input_data['app'] = os.environ.get('app')

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