from repositories.repository import Repository
import pickle

class BinaryFileRepository(Repository):
    def __init__(self,path="src/memoryfiles/binarymemory.bin"):
        self.file_path=path
        self.previous_list_of_expenses=[]
        with open(self.file_path,"ab") as f:
            pass
    def insert_element(self, expense):
        """
        :params:
            expense - Expense
        The function appends the current state of the repo to the stack
        The function takes the expense and dumps it into the file indicated by the file_path as a binary representation
        """
        self.previous_list_of_expenses.append(self.get_elements())
        with open(self.file_path,"ab") as f:
            pickle.dump(expense,f)
    def get_elements(self):
        list_of_expenses=[]
        with open(self.file_path,"rb") as f:
            while True:
                try:
                    list_of_expenses.append(pickle.load(f))
                except EOFError:
                    break
        return list_of_expenses
    def filter_elements(self, value):
        self.previous_list_of_expenses.append(self.get_elements())
        list_of_expenses=[]
        with open(self.file_path,"rb") as f:
            while True:
                try:
                    expense=pickle.load(f)
                    if expense.get_money()<value:
                        continue
                    list_of_expenses.append(expense)
                except EOFError:
                    break
        with open(self.file_path,"wb") as f:
            for expense in list_of_expenses:
                pickle.dump(expense,f)
    def undo(self):
        with open(self.file_path,"wb") as f:
            for expense in self.previous_list_of_expenses.pop():
                pickle.dump(expense,f)

