import datetime

class DataUI:

    # Filter for selections that allow
    def selectionChooser(self, fullList):
        print("Please make a selection")
        print(" [1]: Show all ")
        print(" [2]: Show per truck")
        print(" [3]: Show package")
        SubMenuTreeSelection = input("")
        selection = []
        if "1" in SubMenuTreeSelection:
            selection = fullList
        if "2" in SubMenuTreeSelection:
            print("Choose a truck ID [1,2,3]")
            choice = input("")
            for pkg in fullList:
                if choice in pkg.truckId:
                    selection.append(pkg)
        if "3" in SubMenuTreeSelection:
            print("Choose a package ID [0..39]")
            choice = input("")
            for pkg in fullList:
                if choice == str(pkg.id):
                    selection.append(pkg)
        return selection
    
    # Shows information about trucks
    def Trucks(self, truck1, truck2, truck3):
        trucks = [truck1, truck2, truck3]
        print("")
        for i,v in enumerate(trucks):
            startTime = "Pending"
            endTime = "Pending"
            if v.startTime != None:
                startTime = v.startTime.strftime('%H:%M')
                if len(v.packages) == 0:
                    endTime = v.getTimeOfDay().strftime('%H:%M')

            print(f"Truck [{v.id}] | "
                f"Mileage: {v.mileage:.2f} | "
                f"Departure: {startTime} | "
                f"Arrival: {endTime} | "
                f"DriveTime: {v.getDriveTime()} mintes")
        print("")

    # Shows information about packages
    def Packages(self, package_hash):
        selection = self.selectionChooser(package_hash)
        print("")
        for i,v in enumerate(selection):
            truckID = v.truckId
            if truckID == -1:
                truckID = "None"
            print(f"[{v.id:2}] | "
                f"[DeliveryNumber]: {v.deliveryNumber:2} | "
                f"[onTruck]: {truckID:4} | "
                f"[Address]: {v.address[:20]:20} | "
                f"[Status]: {v.status:10} | "
                f"[Note]: {v.notes:10}")
        print("")

    # Shows information about delivery times and deadlines
    def DeliveryTime(self, package_hash):
        selection = self.selectionChooser(package_hash)
        print("")
        for i,v in enumerate(selection):
            deadline = v.deadline
            metDeadline = "False"
            if isinstance(v.deadline, datetime.time):
                deadline = v.deadline.strftime('%H:%M')    
                if v.timeStart != None and v.timeEnd != None:
                    if v.timeEnd <= v.deadline:
                        metDeadline = "True"
                        if v.deadline == datetime.time(23,59):
                            deadline = "EOD"
            startTime = "Pending"
            if v.timeStart != None:
                startTime = v.timeStart.strftime('%H:%M')
            endTime = "Pending"
            if v.timeEnd != None:
                endTime = v.timeEnd.strftime('%H:%M')
            print(f"[{v.id:2}] | "
                f"[StartTime]: {startTime:8} | "
                f"[DelivedTime]: {endTime:8} | "
                f"[Deadline]: {deadline:8} | "
                f"[MetDeadline]: {metDeadline:5} | "
                f"[Note]: {v.notes:10}")
        print("")
    
    # Main prompt for the UI
    def MainSelectionPrompt(self, truck1, truck2, truck3, package_hash):
        while True:
            print("Please make a selection")
            print(" [1]: Show stats for trucks")
            print(" [2]: Show stats for packages")
            print(" [3]: Check delivery times")
            print(" [4]: Total Mileage for trucks")
            print(" [5]: Cancel")
            MenuTreeSelection = input("")
            if "1" in MenuTreeSelection:
                self.Trucks(truck1, truck2, truck3)
            elif "2" in MenuTreeSelection:
                self.Packages(package_hash)
            elif "3" in MenuTreeSelection:
                self.DeliveryTime(package_hash)
            elif "4" in MenuTreeSelection:
                totalDistance = truck1.mileage + truck2.mileage + truck3.mileage
                print(f"\nTotal Mileage for all trucks: {totalDistance:.2f} miles\n")
            elif "5" in MenuTreeSelection:
                break

    # Prompt for pausing the simulation and opening the menu for stats at specific times
    def TimePrompt(self, currentTime: datetime.time, truck1, truck2, truck3, package_hash) -> datetime.time:
        while True:
            print(" [1]: Pause the simulation at a point in time")
            print(" [2]: Run the simulation to the end")
            print(" [3]: View stats for this moment in time")
            
            selectionInput = input("")
            if "1" in selectionInput:
                while True:
                    print("Please input a time in format of [hh:mm] or type 'back' to return to menu")
                    timeInput = input("")
                    
                    if timeInput.lower() == 'back':
                        break
                    
                    try:
                        time = timeInput.split(":")
                        hour = int(time[0])
                        minute = int(time[1])
                        
                        chosenTime = datetime.time(hour, minute)
                        if chosenTime > currentTime:
                            print(f"Simulation set to pause at {hour:02}:{minute:02}")
                            return chosenTime
                        else:
                            print(f"Error: Time must be later than {currentTime.strftime('%H:%M')}.")
                            
                    except ValueError:
                        print(f"Invalid format '{timeInput}'. Use HH:MM (e.g., 10:30).")
            elif "2" in selectionInput:
                print("Running simulation until the end of the day.")
                return datetime.time(23, 59)
            elif "3" in selectionInput:
                self.MainSelectionPrompt(truck1, truck2, truck3, package_hash)
            else:
                print("Invalid selection. Please choose 1, 2, or 3.")