from datetime import date
from reservation import Reservation

class Repository:
    def __init__(self,path) -> None:
        self.path = path
        self.__data = []
        self._rooms=[]
        self.__load()
        self.__load_rooms()
    def __load(self):
        with open(self.path,"r") as file:
            for line in file:
                res=line.strip().split(",")
                self.__data.append(Reservation(res[0],res[1],res[2],res[3],res[4],date.fromisoformat(res[5]),date.fromisoformat(res[6])))
    def __save(self):
        with open(self.path,"w") as file:
            for data in self.__data:
                l=[str(data.id),data.last_name,data.first_name,data.room_type,data.guests,str(data.start_date),str(data.end_date)]
                file.write(",".join(l)+"\n")
    
    def __load_rooms(self):
        with open("room_types.txt","r") as file:
            for line in file:
                self._rooms.append(line.strip().split(","))
    
    def add_reservation(self,reservation):
        """
        :params:
            reservation: Reservation
        :return:
            None
        
        Function that adds a reservation to the repository. Raises ValueError if the reservation already exists or if there is not enough space for the guests
        """
        for res in self.__data:
            if res.id==reservation.id:
                raise ValueError("Reservation already exists")
        if int(reservation.guests)>int(self._rooms[int(reservation.room_type)-1][1]):
            raise ValueError("Not enough space for the guests")
        self.__data.append(reservation)
        self.__save()
    def get_all(self):
        return self.__data
    def get_by_date(self,start,end):
        return [reservation for reservation in self.__data if (reservation.start_date>=start and reservation.start_date<=end) or (reservation.end_date<=end and reservation.end_date>=start)]
    def delete_reservation(self,id):
        for reservation in self.__data:
            if reservation.id==id:
                self.__data.remove(reservation)
                self.__save()
                return
        raise ValueError("Reservation not found")
    
    def get_empty_rooms(self,start,end):
        """
        :params:
            start: date
            end: date
        :return:
            list of room types that are empty
        """
        room_types = ["01","02","03","04","05"]
        for reservation in self.__data:
            if (reservation.start_date>=start and reservation.start_date<=end) or (reservation.end_date<=end and reservation.end_date>=start):
                if reservation.room_type in room_types:
                    room_types.remove(reservation.room_type)
        return room_types
