from typing import Dict
from loguru import logger
from pymongo import MongoClient
from scripts.constants.app_configuration import Mongo


class MongoConnect:
    def __init__(self, uri, database, collection):
        try:
            self.uri = uri
            self.client = MongoClient(self.uri, connect=False)
            self.database = database
            self.collection = collection
        except Exception as e:
            logger.exception(f'Exception - {e}')

    @staticmethod
    def data_dict(data, city):
        try:
            req_dict = dict()
            req_dict['project_id'] = Mongo.project_id
            req_dict['id'] = Mongo.query_filter
            req_dict['city'] = city
            req_dict['input_data'] = data
            return req_dict
        except Exception as e:
            logger.exception(f'Exception - {e}')

    def insert_one(self, data, city):
        try:
            db = self.client[self.database]
            collection = db[self.collection]
            req_dict = self.data_dict(data=data, city=city)
            response = collection.insert_one(req_dict)
            return response.inserted_id
        except Exception as e:
            logger.exception(f'Exception - {e}')

    def find_one(self, query, filter_dict=None):
        try:
            if filter_dict is None:
                filter_dict = {"_id": 0}
            db = self.client[self.database]
            collection = db[self.collection]
            response = collection.find_one(query, filter_dict)
            return response
        except Exception as e:
            logger.exception(f'Exception - {e}')
