from pymongo import MongoClient
from domain.domain import Expense

class DatabaseRepository():
    def __init__(self):
        self.connection_string="mongodb://DanielCujba:kT99aAmXD2DXXru@ac-72p9ntw-shard-00-00.c6jcmwa.mongodb.net:27017,ac-72p9ntw-shard-00-01.c6jcmwa.mongodb.net:27017,ac-72p9ntw-shard-00-02.c6jcmwa.mongodb.net:27017/?ssl=true&replicaSet=atlas-a0t2fd-shard-0&authSource=admin&retryWrites=true&w=majority"
        self.client = MongoClient(self.connection_string)
        self.db = self.client['FP']
        self.collection=self.db['Expenses']
        self.undos=[]
    def insert_element(self,expense):
        id_inserted=self.collection.insert_one(self.toJson(expense)).inserted_id
        self.undos.append(id_inserted)
    def get_elements(self):
        return [Expense(int(element["day"]),int(element["money"]),element["type_of_expense"]) for element in self.collection.find()]
    def filter_elements(self,value):
        self.undos.append([el for el in self.collection.find({"money":{"$lt":value}})])
        self.collection.delete_many({"money":{"$lt":value}})
    def undo(self):
        e=self.undos.pop()
        if type(e)==list:
            self.collection.insert_many(e)
        else:
            self.collection.delete_one({"_id":e})
    def toJson(self,expense):
        return {"day":expense.get_day(),"money":expense.get_money(),"type_of_expense":expense.get_type_of_expense()}
