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


class TextFileRepository(Repository):
    def __init__(self,path="src/memoryfiles/textmemory.txt"):
        self.file_path=path
        self.previous_list_of_expenses=[]
        with open(self.file_path,"a") as f:
            pass
    def insert_element(self, expense):
        """
        :params:
            expense - Expense
        The function appends the current state of the repo on the stack
        The function takes an expense and stores it in the format "{day} {money} {type_of_expense}" in the text file indicated by the file_path
        """
        self.previous_list_of_expenses.append(self.get_elements())
        with open(self.file_path,"a") as f:
            f.write("{} {} {}\n".format(expense.get_day(),expense.get_money(),expense.get_type_of_expense()))
    def get_elements(self):
        list_of_expenses=[]
        with open(self.file_path,"r") as f:
            for line in f:
                data=line.strip().split(' ',2)
                list_of_expenses.append(Expense(int(data[0]),int(data[1]),data[2]))
        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,'r') as f:
            for line in f:
                data=line.strip().split(' ',2)
                if int(data[1])<value:
                    continue
                list_of_expenses.append(Expense(int(data[0]),int(data[1]),data[2]))
        with open(self.file_path,'w') as f:
            for expense in list_of_expenses:
                f.write("{} {} {}\n".format(expense.get_day(),expense.get_money(),expense.get_type_of_expense()))
    def undo(self):
        with open(self.file_path,'w') as f:
            for expense in self.previous_list_of_expenses.pop():
                f.write("{} {} {}\n".format(expense.get_day(),expense.get_money(),expense.get_type_of_expense()))

    