import datetime

from flask import request

from scripts.config import app_constants
from scripts.config.db_connection_obj import ConnectionObj
from scripts.logging.logger import logger
from scripts.utils.mongo_utility import MongoConnect


class CommonUtils:
    def __init__(self):
        self.mongo_obj = ConnectionObj.mongo_connection_obj
        if not ConnectionObj.mongo_connection_obj:
            self.mongo_obj = ConnectionObj.mongo_connection_obj = MongoConnect()
        self.metadata = app_constants.DBMapping.mongo_db_name
        self.user_collection = app_constants.DBMapping.user

    @staticmethod
    def get_meta_information(user_id, existing_meta=None):
        present_time = datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S")
        if existing_meta is None:
            meta_information = {
                "created_by": user_id,
                "created_time": present_time,
                "last_updated_by": user_id,
                "last_updated_time": present_time
            }
        else:
            meta_information = existing_meta
            meta_information["last_updated_by"] = user_id
            meta_information["last_updated_time"] = present_time
        return meta_information

    def get_site_template(self, project_id):
        site_tmpl_list = []
        key_list = []
        try:
            data = self.mongo_obj.find_one(app_constants.DBMapping.mongo_db_name,
                                           app_constants.DBMapping.customer_projects,
                                           {"customer_project_id": project_id})
            templat_id = data["site_templt_id"]
            templat_constant = self.mongo_obj.find_one(app_constants.DBMapping.mongo_db_name,
                                                       app_constants.DBMapping.constants,
                                                       {"type": "site_template"}, {"_id": 0})
            if templat_constant:
                for i in templat_constant["data"]:
                    if templat_id == i["site_templt_id"]:
                        key_list = i["key_list"]
                        site_tmpl_list = i["value"]
                        break
        except Exception as e:
            print(e)
        return site_tmpl_list, key_list

    def get_process_template(self, project_id):
        site_tmpl_list = []
        key_list = []
        try:
            data = self.mongo_obj.find_one(app_constants.DBMapping.mongo_db_name,
                                           app_constants.DBMapping.customer_projects,
                                           {"customer_project_id": project_id})
            templat_id = data["process_templt_id"]
            templat_constant = self.mongo_obj.find_one(app_constants.DBMapping.mongo_db_name,
                                                       app_constants.DBMapping.constants,
                                                       {"type": "process_template"}, {"_id": 0})
            if templat_constant:
                for i in templat_constant["data"]:
                    if templat_id == i["process_templt_id"]:
                        key_list = i["key_list"]
                        site_tmpl_list = i["value"]
                        break
        except Exception as e:
            print(e)
        return site_tmpl_list, key_list

    @staticmethod
    def get_user_id(input_data=None):
        if "user_id" in request.cookies:
            user_id_from_cookies = request.cookies.get("user_id")
            # if enable_security:
            #     session_id = request.cookies.get("session_id")
            #     key = session_id[:16]
            #     user_id = AESCipher(key).decrypt(user_id_from_cookies)
            # else:
            user_id = user_id_from_cookies
            return {"status": "success", "user_id": user_id}
        else:
            if "user_id" in input_data and input_data["user_id"] != "":
                user_id = input_data["user_id"]
                return {"status": "success", "user_id": user_id}
            else:
                return {"status": "failed", "message": "user_id is missing from input"}

    def get_user_name_for_user_id(self, user_id):
        user_name = ""
        try:
            user_name_object = ConnectionObj.mongo_connection_obj.find_one(db_name=self.metadata,
                                                                           collection_name=self.user_collection,
                                                                           query={"user_id": user_id},
                                                                           search_json={"_id": 0, "username": 1})
            if user_name_object is not None:
                return user_name_object["username"]
            else:
                return user_name
        except Exception as e:
            logger.exception("exception while fetching user name for the given user_id:" + str(e))
            return user_name

    @staticmethod
    def field_validator_with_empty_space(field_list, json_content):
        fields_in_json_content = json_content.keys()
        for field in field_list:
            if field in fields_in_json_content:
                if type(json_content[field]) is str and json_content[field].strip(
                        " ") == "":
                    return field
                else:
                    continue
            else:
                return field
