from repositories.repository import Repository
from domain.domain import Expense
import json

class JsonFileRepository(Repository):
    def __init__(self):
        self.file_path="src/memoryfiles/jsonmemory.json"
        self.previous_list_of_expenses=[]
        with open(self.file_path,"a") as f:
            pass
    def insert_element(self, expense):
        expenses=None
        with open(self.file_path,"r") as f:
            expenses=json.load(f)
        self.previous_list_of_expenses.append(expenses)
        expenses.append(self.toJson(expense))
        with open(self.file_path,"w") as f:
            json.dump(expenses,f,indent=4)
    def get_elements(self):
        with open(self.file_path,"r") as f:
            json_obj=json.load(f)
            return [Expense(int(expense["day"]),int(expense["money"]),expense["type_of_expense"]) for expense in json_obj]
    def filter_elements(self, value):
        expenses=None
        with open(self.file_path,"r") as f:
            expenses=json.load(f)
        self.previous_list_of_expenses.append(expenses)
        expenses=[expense for expense in expenses if expense["money"]>=value]
        with open(self.file_path,"w") as f:
            json.dump(expenses,f,indent=4)
    def undo(self):
        with open(self.file_path,"w") as f:
            json.dump(self.previous_list_of_expenses.pop(),f,indent=4)
    def toJson(self,expense):
        return {"day":expense.get_day(),"money":expense.get_money(),"type_of_expense":expense.get_type_of_expense()}