import pymongo
from constant import mongodb_config


class MongodbDAO:
    _dao = None

    @classmethod
    def to_instance(cls):
        if MongodbDAO._dao is None:
            MongodbDAO._dao = MongodbDAO()
        return MongodbDAO._dao

    def __init__(self):
        MongodbDAO._dao = self
        self.client = pymongo.MongoClient(mongodb_config['url'])
        self.db = self.client[mongodb_config['db']]

    def to_db(self, db=None):
        if db is not None:
            self.db = self.client[db]
        return self.db

    def close(self):
        return self.client.close()
