o
    Uh
                     @   sd   U d dl mZ d dlmZ d dlmZ d dlmZ d dlm	Z	 e	e
ZdZeed< G dd	 d	ZdS )
    )MongoClient)
Collection)Database)settings)
get_loggerN	db_clientc                       s   e Zd ZU dZdZeed<  fddZdefddZ	de
defd	d
ZdedefddZde
dedefddZdefddZ  ZS )MongoDBSingletonN_clientc                    s:   | j d u rt | | _ tj}t|| j _td | j S )NzConnected to MongoDB)		_instancesuper__new__r   MONGODB_URIr   r	   loginfo)clsconnection_string	__class__ 2/var/www/html/RetailAPI/app/database/main/mongo.pyr      s   

zMongoDBSingleton.__new__returnc                 C   s   t j}| j| S )N)r   
MONGODB_DBr	   )selfdb_namer   r   r   get_main_db   s   
zMongoDBSingleton.get_main_dbcollection_namec                 C   s&   |   }|| vr|| || S )z(Get a collection from the main database.)r   list_collection_namescreate_collection)r   r   dbr   r   r   get_collection   s   
zMongoDBSingleton.get_collection
collectionc                 C   s   | d|iS )a  
        Retrieves an existing document from a MongoDB collection.

        Args:
            collection (Collection): The MongoDB collection.
            identifier: The identifier of the document.

        Returns:
            dict: The existing document if found, else None.
        _id)find_one)r   r    
identifierr   r   r   get_existing_document#   s   z&MongoDBSingleton.get_existing_documentr#   c                 C   s2   t |ttfstd| |}|d|iduS )a  
        Checks if data exists in a MongoDB collection.

        Args:
            collection_name (str): The name of the collection.
            identifier: The identifier of the document.

        Returns:
            bool: True if data exists, False otherwise.
        z(Identifier must be an integer or string.r!   N)
isinstanceintstr	TypeErrorr   r"   )r   r   r#   r    r   r   r   is_data_in_db0   s   
zMongoDBSingleton.is_data_in_dbc                    sD   |  ||}|r|d|id|i d S d|i|}|| d S )Nr!   z$set)r$   
update_one
insert_one)r   r    r#   dataexisting_documentnew_documentr   r   r   insert_or_update_documentB   s   z*MongoDBSingleton.insert_or_update_document)__name__
__module____qualname__r
   r	   r   __annotations__r   r   r   r'   r   r   dictr$   r&   boolr)   r/   __classcell__r   r   r   r   r      s   
 r   )pymongor   pymongo.collectionr   pymongo.databaser   
app.configr   app.logr   r0   r   r   r3   r   r   r   r   r   <module>   s    