from domain import Address

class Repo:
    def __init__(self,path) -> None:
        self.path=path
        self.addresses=[]
        self.load_file()

    def load_file(self):
        with open(self.path,"r") as f:
            for line in f:
                attributes=line.split(",")
                self.addresses.append(Address(int(attributes[0]),attributes[1],int(attributes[2]),int(attributes[3]),int(attributes[4])))

    def save_file(self):
        with open(self.path,"w") as f:
            for address in self.addresses:
                string_address = str(address.get_id())+","+str(address.get_name())+","+str(address.get_number())+","+str(address.get_x())+","+str(address.get_y())+"\n"
                f.write(string_address)

    def add_address(self,address_to_add):
        for address in self.addresses:
            if address.get_id() == address_to_add.get_id():
                raise ValueError("Id of address already exists")
        self.addresses.append(address_to_add)
        self.save_file()

    def get_addresses_as_string(self):
        string_of_addresses=""
        for address in self.addresses:
            string_of_addresses+=str(address)
            string_of_addresses+="\n"
        return string_of_addresses
        
    def get_addresses(self):
        return self.addresses