Esempio n. 1
0
    def __init__(self):
        '''Instances of appropriate classes created in constructor so the class
               has access to their functions. MainLL connects the class to the logic layer
               and the other classes handle inputs, outputs and errors'''
        self.mainObject = MainLL()
        self.inputObject = InputHandler()
        self.outputObject = OutputHandler()

        self.MAINMENU = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                      Destinations                        #
#                                                          #  
#                  1. All destinations                     #
#                  2. Add a new destination                #             
#                  3. Update destination                   #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #	
#  back(b)                                                 #
############################################################
"""
        self.start()
Esempio n. 2
0
    def __init__(self):
        ''' Appropriate classes initiated in constructor so the airplaneUI has access to 
            them. mainObject connects it to the MainLL class and so on.'''

        self.mainObject = MainLL()
        self.inputObject = InputHandler()
        self.outputObject = OutputHandler()
        self.errorObject = ErrorHandler()
        self.MAINMENU = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                                                          #
#                       Airplanes                          #
#                                                          #
#                   1. List Airplanes                      #
#                   2. Add airplanes                       #
#                   3. Airplane status                     #
#                   4. Add licensed pilot                  #
#                   5. Licensed pilots                     #
#                   6. Find airplane by ID                 #
#                   7. Number of flights by Airplane       #
#                                                          #
#                                                          #
#                                                          #
#  back(b)                                                 #
############################################################
"""
        # start called in constructor so that start runs as son as AirplaneUI instance is initiated.
        self.start()
Esempio n. 3
0
    def __init__(self):
        self.mainObject = MainLL()
        self.inputObject = InputHandler()
        self.outputObject = OutputHandler()

        self.MAINMENU = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                                                          #
#                         Voyage                           #
#                                                          #
#                      1.List voyages                      #
#                      2.Add voyage                        #
#                      3.Complete voyage                   #
#                      4.Most popular voyage               #
#                                                          #
#                                                          #
#                                                          #				
#                                                          #
#  back(b)                                                 #
############################################################	"""
        self.start()
Esempio n. 4
0
class DestinationUI():
    ''' Destination UI has method to get, add and update destinations'''
    def __init__(self):
        '''Instances of appropriate classes created in constructor so the class
               has access to their functions. MainLL connects the class to the logic layer
               and the other classes handle inputs, outputs and errors'''
        self.mainObject = MainLL()
        self.inputObject = InputHandler()
        self.outputObject = OutputHandler()

        self.MAINMENU = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                      Destinations                        #
#                                                          #  
#                  1. All destinations                     #
#                  2. Add a new destination                #             
#                  3. Update destination                   #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #	
#  back(b)                                                 #
############################################################
"""
        self.start()

    def start(self):

        while True:
            print(self.MAINMENU)
            mainCommand_dict = {
                '1': self.getAllDestiantionUI,
                '2': self.addNewDestinationUI,
                '3': self.updateDestinationUI,
                'q': QuitUI
            }
            user_input = input("Input a command: ")
            if user_input != 'b':
                if user_input in mainCommand_dict:
                    for key in mainCommand_dict:
                        if user_input == key:
                            mainCommand_dict[key]()
                else:
                    print('Invalid command!')
            else:
                return

    def getAllDestiantionUI(self):
        destinationObject_list = self.mainObject.getAllDestinationsLL()
        return self.outputObject.allDestinationsOH(destinationObject_list)

    def addNewDestinationUI(self):
        newDestination = self.inputObject.addNewDestinationIH()
        destinationID = self.mainObject.generadeDestinationIdLL()
        newDestination.setDestinationId(destinationID)
        self.mainObject.addNewDestinationLL(newDestination)

    def updateDestinationUI(self):
        destinationObject_dict = {}  # Option dictionary for user
        destinationObject_list = self.mainObject.getAllDestinationsLL()
        for counter, destination in enumerate(destinationObject_list, 1):
            destinationObject_dict[str(counter)] = destination
        self.outputObject.availableDestinationsOH(destinationObject_dict)
        dataList = self.inputObject.updateDestinationIH(destinationObject_dict)
        self.mainObject.updateDestinationLL(dataList)
Esempio n. 5
0
class VoyageUI:
    def __init__(self):
        self.mainObject = MainLL()
        self.inputObject = InputHandler()
        self.outputObject = OutputHandler()

        self.MAINMENU = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                                                          #
#                         Voyage                           #
#                                                          #
#                      1.List voyages                      #
#                      2.Add voyage                        #
#                      3.Complete voyage                   #
#                      4.Most popular voyage               #
#                                                          #
#                                                          #
#                                                          #				
#                                                          #
#  back(b)                                                 #
############################################################	"""
        self.start()

    def start(self):
        '''We create a command dictonary to avoid conditional statements. The function will run the corrosponding submenu '''
        while True:
            mainCommand_dict = {'1': self.getVoyagesUI, '2': self.addNewVoyageUI, '3': self.completeVoyageUI, '4':self.popularVoyageUI,'q': QuitUI}
            print(self.MAINMENU)
            user_input = input("Input a command: ")
            if user_input != 'b':               # we chose b as a back button.
                if user_input in mainCommand_dict:
                    for key in mainCommand_dict:
                        if user_input == key:
                            mainCommand_dict[key]()
                else:
                    print('Invalid command!')
            else:
                return

    def popularVoyageUI(self):
        '''Goes through our voyages and creates a dictionary. Prints out the most popular voyage.'''
        voyageObject_list = self.mainObject.getVoyageLL()
        flights_dict = {}
        for voyage in voyageObject_list:
            if voyage.getArrivingAt() not in flights_dict:
                flights_dict[voyage.getArrivingAt().lower()] = 1
            else:
                flights_dict[voyage.getArrivingAt().lower()] += 1
        del flights_dict["keflavik"]
        maximum = max(flights_dict, key=flights_dict.get)

        print("The most popular destination is {}, with {} flights!".format(maximum,flights_dict[maximum]))
        input("Press any key to continue: ")   
            
    def getVoyagesUI(self):
        voyageObject_list = self.mainObject.getVoyageLL()   #  Gets information needed from getvoyage logic layer.
        self.outputObject.allVoyagesOH(voyageObject_list)
    
    def addNewVoyageUI(self):
        """ This method adds a voyage. The user only inputs the destination and when he wants to fly, the rest is generated
          for him trough out the method. After creating the first flight the returning flight also generates for him.
          We call various error checkers trought out the process. The method returns 2 flights """
        print()
        print(' ____________________ Create a Voyage_______________________ ')
        print("           Pick a destination that Nan Air flys to:")
        destinationObject_list = self.mainObject.getAllDestinationsLL()
        self.outputObject.voyageDestinationOH(destinationObject_list)
        destDict = {}
        for i, dest in enumerate(destinationObject_list):   # makes a dictionary containing destinations for the user
            if dest.getCountry() == "keflavik":             # we cant fly from kef to kef
                pass
            else:
                destDict[i] = dest.getCountry()
        departingFromKef = "keflavik"
        pickDest = int(input("Where will you be arriving at: "))
        if pickDest not in destDict.keys():                 #
            print("Sorry you entered an invalid destination.")
            return None
        firstFlight = self.inputObject.addNewFlightIH()
        firstFlight.setDepartingFrom(departingFromKef)      # First flight always departs from kef
        firstFlight.setArrivingAt(destDict[pickDest])
        if self.mainObject.errorCheckDateLL(firstFlight) == False:
            return None
        if self.mainObject.flightCollisionLL(firstFlight) == True:
            print("You will cause a collision, do you really want to do that?")
            print("Every flight must have at least one minute between them.")
            return None
        arrivalTime = self.mainObject.findArrivalTimeLL(firstFlight)
        if arrivalTime != False:
            firstFlight.setArrivalTime(str(arrivalTime))
        else:
            print("Sorry you entered an invalid destination.")
            return None
        assignedAirplane = self.mainObject.findAvalibleAirplanesLL(firstFlight)
        if assignedAirplane != False:
            firstFlight.setAircraftId(str(assignedAirplane))
        else:
            print("Sorry, there are no avalible airplanes at this Time :(")
            return None
        firstFlightId = self.mainObject.generateFlightNumberLL(firstFlight)
        if firstFlightId != False:
            firstFlight.setFlightNumber(str(firstFlightId))

        else:
            print(firstFlight.getArrivingAt(), "is not a valid destination.")
            return None
        self.mainObject.addNewVoyageLL(firstFlight)

        departingFrom, arravingAt, DeparturTime, airplaneId = self.mainObject.generateSecondFlightLL(firstFlight)
        secondFlight = VoyageData("", departingFrom, arravingAt, DeparturTime, "", airplaneId)
        secondFlightId = self.mainObject.generateFlightNumberLL(firstFlight)
        arrivalTimeSecondFlight = self.mainObject.findArrivalTimeLL(secondFlight)
        secondFlight.setFlightNumber(str(secondFlightId))

        secondFlight.setArrivalTime(arrivalTimeSecondFlight)
        self.mainObject.addNewVoyageLL(secondFlight)
        print()
        print("New Voyage saved! You can complete it now in 'complete voyage'.")
        input("Press any key to continue.")


    def completeVoyageUI(self):
        ''' User picks a voyage to complete. The method completeVoyageUI lets user pick pilots with license to the
        voyges airplane and also available staff. For each position to be filled we create a dictionary so the user
        can simply choose a employee by putting in a number'''
        counter = 0
        voyageDict = {}
        flightObject_list = self.mainObject.getVoyageLL()
        for number1, flight1 in enumerate(flightObject_list):
            for number2, flight2 in enumerate(flightObject_list):
                if number2 - number1 == 1 and number1 % 2 == 0:
                    if flight1.getCaptain() == "" and flight2.getCaptain() == "":   # if there is no captain then the voyage has not been staffed
                        counter += 1
                        voyageDict[str(counter)] = [flight1, flight2]
                        flightTime = flight1.getDepartureTime().split("T")
                        # When printing each voyage we make sure with the for loops we only print 2 lines(1 voyage) at a time
                        print("{}. {} ---> {} | {} ---> {}\n   {} {} {}\n".format(counter, flight1.getDepartingFrom(),
                        flight1.getArrivingAt(),flight2.getDepartingFrom(), flight2.getArrivingAt(), "Departing at", flightTime[0], flightTime[1]))
        print("Press 0 if your want to cancel.")
        if voyageDict == {}:
            print("There are no voyages to complete!")
            return None
        pickVoyage = input("Pick a voyage to complete: ").strip()
        if pickVoyage != 0:
            if pickVoyage in voyageDict:
                for key, val in voyageDict.items():
                    if pickVoyage == key:
                        pilotObject_list = self.mainObject.getAllPilotsLL()
                        cabinCrewObject_list = self.mainObject.getAllCabinCrewLL()
                        staffObject_list = self.mainObject.getAllStaffLL()

                        staff_list = []
                        print("\n______ Available Captains ______")
                        availableCaptains = self.mainObject.getAvailableCaptainsLL(val[0])
                        captainDict = {}
                        for i, captain in enumerate(availableCaptains, 1):
                            captainDict[str(i)] = captain.getName()
                            print(str(i) + ".",captain.getName())
                        captainOfChoice = input("\nEnter a Captain: ").strip()
                        while captainOfChoice not in captainDict:
                            print(ERRORMESSAGESTAFF)
                            captainOfChoice = input("\nEnter a Captain: ").strip()
                        staff_list.append(captainDict[captainOfChoice])

                        print("\n______ Available Co-Pilots ______")
                        coPilotDict = {}
                        availableCoPilots = self.mainObject.getAvailableCoPilotsLL(val[0])
                        for k, coPilot in enumerate(availableCoPilots, 1):
                            coPilotDict[str(k)] = coPilot.getName()
                            print(str(k) + ".",coPilot.getName())
                        coPilotOfChoice = input("\nEnter a Co-Pilots: ").strip()
                        while coPilotOfChoice not in coPilotDict:
                            print(ERRORMESSAGESTAFF)
                            coPilotOfChoice = input("\nEnter a Co-Pilots: ").strip()
                        staff_list.append(coPilotDict[coPilotOfChoice])

                        print("\n ______ Available flight service managers ______")
                        fsmDict = {}
                        availableFlightServicerManagers = self.mainObject.getAvailableFlightServiceManagersLL(val[0])
                        for x, flightServiceManager in enumerate(availableFlightServicerManagers, 1):
                            fsmDict[str(x)] = flightServiceManager
                            print(str(x) + ".", flightServiceManager)

                        fsmOfChoice = input("\nEnter a flight service manager: ").strip()
                        while fsmOfChoice not in fsmDict:
                            print(ERRORMESSAGESTAFF)
                            fsmOfChoice = input("\nEnter a flight service manager: ").strip()
                        staff_list.append(fsmDict[fsmOfChoice])

                        print("\n ______ Available flight attendants ______")
                        cabinCrewDict = {}
                        availableFlightAttendants = self.mainObject.getAvailableFlightAttendantsLL(val[0])
                        for l, flightAttendant in enumerate(availableFlightAttendants, 1):
                            cabinCrewDict[str(l)] = flightAttendant
                            print(str(l) + ".", flightAttendant)
                        attendatOfChoice = input("\nEnter a flight attendant:  ")
                        while attendatOfChoice not in cabinCrewDict:
                            print(ERRORMESSAGESTAFF)
                            attendatOfChoice = input("\nEnter a flight attendant:  ")
                        staff_list.append(cabinCrewDict[attendatOfChoice])
                        print("Voyage has been completed!")
                        errorChecked = self.inputObject.updateVoyageIH(staff_list, pilotObject_list, cabinCrewObject_list, staffObject_list)
                        self.mainObject.updateVoyageLL(val, errorChecked)

            else:
                print("Invalid Voyage.")
        else:
            return
Esempio n. 6
0
class StaffUI:
    '''Instances of appropriate classes created in constructor so the class 
       has access to their functions. MainLL connects the class to the logic layer
       and the other classes handle inputs, outputs and errors'''
    def __init__(self):
        self.mainObject = MainLL()
        self.inputObject = InputHandler()
        self.outputObject = OutputHandler()
        self.errorObject = ErrorHandler()

        self.MAINMENU = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                                                          #
#                        Employees                         #
#                                                          #
#                  1. List employees                       #
#                  2. Register employees                   #
#                  3. Work Schedule                        #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#  back(b)                                                 #
############################################################
"""
        self.SUBMENU1 = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                                                          #
#                                                          #
#                        Employees                         #
#                                                          # 
#                   1. All employees                       #
#                   2. Pilots                              #
#                   3. Cabin Crew                          #
#                   4. Find employee                       #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#  back(b)                                                 #
############################################################"""

        self.SUBMENU2 = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                                                          #
#                                                          #
#                      Work schedule                       #
#                                                          # 
#               1. Find available staff                    #
#               2. Work schedule by date                   #
#               3. Work schedule for single employee       #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#  back(b)                                                 #
############################################################"""
        '''Start function called in constructor so that as soon as the class is
           initiated start function runs'''
        self.start()

    def start(self):
        while True:
            # dictionary with class functions as values and available user inputs as keys
            mainCommand_dict = {
                '1': self.listStaffUI,
                '2': self.addNewStaffUI,
                '3': self.workScheduleUI,
                'q': QuitUI
            }
            print(self.MAINMENU)
            user_input = input("Input a command: ")

            # Handles user input, calls appropriate function if user input is key in dict
            if user_input != 'b':
                if user_input in mainCommand_dict:
                    for key in mainCommand_dict:
                        if user_input == key:
                            mainCommand_dict[key]()
                else:
                    print('Invalid command!')
            else:
                return

    def listStaffUI(self):

        while True:
            subCommand_dict = {
                '1': self.getAllStaffUI,
                '2': self.getAllPilotsUI,
                '3': self.getAllCabinCrewUI,
                '4': self.getStaffByIdUI,
                'q': QuitUI
            }
            print(self.SUBMENU1)
            user_input = input("Input a command: ")
            if user_input != 'b':
                if user_input in subCommand_dict:
                    for key in subCommand_dict:
                        if user_input == key:
                            subCommand_dict[key]()
                else:
                    print('Invalid command!')
            else:
                return

    def workScheduleUI(self):

        while True:
            subCommand_dict = {
                '1': self.availableStaffUI,
                '2': self.unavailableStaffUI,
                '3': self.singleStaffUI,
                'q': QuitUI
            }
            print(self.SUBMENU2)
            user_input = input('Input a command: ')
            if user_input != 'b':
                if user_input in subCommand_dict:
                    for key in subCommand_dict:
                        if user_input == key:
                            subCommand_dict[key]()
                else:
                    print('Invalid command!')
            else:
                return

    '''Calls MainLL function into variable, passes variable into outputHandler function where
       information is printed'''

    def getAllStaffUI(self):
        staffObject_list = self.mainObject.getAllStaffLL()
        return self.outputObject.allStaffOH(staffObject_list)

    '''Calls MainLL function into variable, passes variable into outputHandler function where
       information is printed'''

    def getAllPilotsUI(self):
        pilotObject_list = self.mainObject.getAllPilotsLL()
        return self.outputObject.allPilotsOH(pilotObject_list)

    '''Calls MainLL function into variable, passes variable into outputHandler function where
       information is printed'''

    def getAllCabinCrewUI(self):
        cabinCrewObject_list = self.mainObject.getAllCabinCrewLL()
        self.outputObject.allCabinCrewOH(cabinCrewObject_list)

    '''Calls input object where user inputs appropriate information and staffObject
       is created. New staff object then passed down into LL through MainLL'''

    def addNewStaffUI(self):
        # newEmployee object created in addNewStaffIH
        newEmployee = self.inputObject.addNewStaffIH()

        # Role of employee checked, if not pilot then license should be N/A
        role = newEmployee.getRole()
        if role == "cabincrew":
            newEmployee.setLicense("N/A")
            self.mainObject.addNewStaffLL(newEmployee)
            print('New staff member registered!')

        # If employee is pilot then airplane license should be added
        else:
            airplaneList = self.mainObject.airplaneObject.getAirplanes()
            airplaneIdList = []
            for airplane in airplaneList:
                airplaneIdList.append(airplane.getPlaneId())
            print("What license does", newEmployee.getName(), "have: ")
            print("{}\n".format(" ".join(i for i in airplaneIdList)))
            staff_license = input("Enter license: ")
            while staff_license not in airplaneIdList:
                print(
                    "\nInvalid license, can only include alphanumerical characters."
                )
                staff_license = input("Enter license: ")
            newEmployee.setLicense(staff_license)

            # New staff object passed down into LL through MainLL
            self.mainObject.addNewStaffLL(newEmployee)
            print('New staff member registered!')

    '''Dictionary created containing all employees as values, numbers as keys. User picks
       employee and chosen employee ssn is passed into getStaffByIdLL which returns desired staff object,
       staff object then passed into outputObject funtion'''

    def getStaffByIdUI(self):
        # Dictionary with number as key and staff object as value created
        staffObject_dict = {}
        staffObject_list = self.mainObject.getAllStaffLL()
        for counter, staffMember in enumerate(staffObject_list, 1):
            staffObject_dict[str(counter)] = staffMember

        # All staff listed and user chooses desired employee
        self.outputObject.singleStaffListOH(staffObject_dict)
        user_input = input("Choose an employee: ")
        errorChecked = self.errorObject.getStaffByIdEH(user_input,
                                                       staffObject_dict)

        # Chosen employee ssn passed into getStaffByID
        staffMember = self.mainObject.getStaffByIDLL(errorChecked.getSSN())

        # staff object passed into outputHandler function
        self.outputObject.singleStaffHeaderOH()
        self.outputObject.singleStaffOH(staffMember)

    '''User picks date, date is passed into workScheduleAvailableLL which returns list of staff
       objects that are not working on given day.'''

    def availableStaffUI(self):
        flag = True
        while flag:
            input_date = input("Enter a date 'YYYY-MM-DD' : ")
            if self.errorObject.errorCheckDateEH(input_date):
                flag = False
            else:
                continue
        availableStaff = self.mainObject.workScheduleAvailableLL(input_date)
        self.outputObject.workScheduleAvailableOH(availableStaff)

    '''Shows user available dates, user picks desired date. date then passed into workScheduleLL
       that returns dictionary with all voyages as keys and staff working the voyages as keys'''

    def unavailableStaffUI(self):
        availableDates_dict = {}
        availableDates_list = self.mainObject.availableDatesLL()
        for counter, date in enumerate(availableDates_list, 1):
            availableDates_dict[str(counter)] = date
        self.outputObject.availableDatesOH(availableDates_dict)

        user_input = input("Choose date: ")
        errorChecked = self.errorObject.availableDatesEH(
            user_input, availableDates_dict)
        workSchedule_dict = self.mainObject.workScheduleLL(errorChecked)
        self.outputObject.allVoyagesOH(workSchedule_dict)

    '''Prompts user for startdate and enddate. User then picks employee he wants to see work schedule for.
       user input and desired dates are passed into workWeekLL which returns object list containing voyage objects'''

    def singleStaffUI(self):
        print('Start of work week')
        dateStart = self.inputObject.workWeekIH()
        print('End of work week')
        dateEnd = self.inputObject.workWeekIH()
        compareDay = dateStart.day + 7
        compareDate = dateStart.replace(day=compareDay)

        # check if input dates are a week
        if dateEnd != compareDate:
            print('That is not a work week!')
        else:
            # dictionary created with numbers as keys and values are staff objects
            staffObject_dict = {}
            staffObject_list = self.mainObject.getAllStaffLL()
            for counter, staffMember in enumerate(staffObject_list, 1):
                staffObject_dict[str(counter)] = staffMember
            self.outputObject.singleStaffListOH(staffObject_dict)

            # user chooses employee, dataList with dates and employee ssn passed into LL
            user_input = input("Choose an employee: ")
            errorChecked = self.errorObject.getStaffByIdEH(
                user_input, staffObject_dict)
            dataList = [dateStart, dateEnd, errorChecked.getSSN()]
            workWeekObject_list = self.mainObject.workWeekLL(dataList)
            self.outputObject.workWeekOH(workWeekObject_list)
Esempio n. 7
0
    def __init__(self):
        self.mainObject = MainLL()
        self.inputObject = InputHandler()
        self.outputObject = OutputHandler()
        self.errorObject = ErrorHandler()

        self.MAINMENU = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                                                          #
#                        Employees                         #
#                                                          #
#                  1. List employees                       #
#                  2. Register employees                   #
#                  3. Work Schedule                        #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#  back(b)                                                 #
############################################################
"""
        self.SUBMENU1 = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                                                          #
#                                                          #
#                        Employees                         #
#                                                          # 
#                   1. All employees                       #
#                   2. Pilots                              #
#                   3. Cabin Crew                          #
#                   4. Find employee                       #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#  back(b)                                                 #
############################################################"""

        self.SUBMENU2 = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                                                          #
#                                                          #
#                      Work schedule                       #
#                                                          # 
#               1. Find available staff                    #
#               2. Work schedule by date                   #
#               3. Work schedule for single employee       #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#                                                          #
#  back(b)                                                 #
############################################################"""
        '''Start function called in constructor so that as soon as the class is
           initiated start function runs'''
        self.start()
Esempio n. 8
0
class AirplaneUI:
    def __init__(self):
        ''' Appropriate classes initiated in constructor so the airplaneUI has access to 
            them. mainObject connects it to the MainLL class and so on.'''

        self.mainObject = MainLL()
        self.inputObject = InputHandler()
        self.outputObject = OutputHandler()
        self.errorObject = ErrorHandler()
        self.MAINMENU = """
############################################################
#                           _|_	               quit(q)     #
#                   --@--@--(_)--@--@--                    #
#__________________________________________________________#
#                                                          #
#                       Airplanes                          #
#                                                          #
#                   1. List Airplanes                      #
#                   2. Add airplanes                       #
#                   3. Airplane status                     #
#                   4. Add licensed pilot                  #
#                   5. Licensed pilots                     #
#                   6. Find airplane by ID                 #
#                   7. Number of flights by Airplane       #
#                                                          #
#                                                          #
#                                                          #
#  back(b)                                                 #
############################################################
"""
        # start called in constructor so that start runs as son as AirplaneUI instance is initiated.
        self.start()

    def start(self):

        while True:
            print(self.MAINMENU)
            #  A dictionary that handles users input.
            mainCommand_dict = {
                '1': self.getAirplanesUI,
                '2': self.registerAirplaneUI,
                '3': self.airplaneStatusUI,
                '4': self.addLicenseUI,
                '5': self.getLicenseDictUI,
                '6': self.getAirplaneByIdUI,
                '7': self.MostpopularUI,
                'q': QuitUI
            }
            user_input = input("Input a command: ")
            if user_input != 'b':
                if user_input in mainCommand_dict:  #  Checks if the users input is correct.
                    for key in mainCommand_dict:
                        if user_input == key:
                            mainCommand_dict[key](
                            )  #  Calls the correct command.
                else:
                    print('Invalid command!')
            else:
                return  #  If user input is 0, returns to main menu.

    '''Calls getAirplanesLL (list of airplane objects) function in mainObject into variable,
     returns function in outputObject'''

    def getAirplanesUI(self):
        airplaneObject_list = self.mainObject.getAirplanesLL()
        return self.outputObject.allAirplanesOH(airplaneObject_list)

    '''Creates list of all voyages (objects), counts how many times each airplane occurrs. Results are put
       into dictionary and contents of dictionary are printed'''

    def MostpopularUI(self):
        voyageObject_list = self.mainObject.getVoyageLL()
        Popular_dict = {}
        for voyage in voyageObject_list:
            if voyage.getAircraftId() not in Popular_dict:
                Popular_dict[voyage.getAircraftId().upper()] = 1
            else:
                Popular_dict[voyage.getAircraftId().upper()] += 1
        print("Number of flights flown by each airplane:")
        for key, val in Popular_dict.items():
            print("The airplane {} has flown {} times.".format(key, val))
        input("Enter any key to continue: ")

    '''Creates dictionary of all airplane objects with numbers as value. User selects desired airplane
       and the selected airplanes id is passed down into the logic layer where the airplane object is found.
       The airplane object is then passed into outputObject where detailed information is printed'''

    def getAirplaneByIdUI(self):
        airplaneIdList = self.mainObject.getAirplanesLL()
        airplaneIdDict = {}
        for i, airplane in enumerate(airplaneIdList, 1):
            airplaneIdDict[str(i)] = airplane.getPlaneId()
        self.outputObject.singleAirplanelistOH(airplaneIdList)
        input_airId = input("Enter Airplane ID number: ")
        while input_airId not in airplaneIdDict:
            print("Sorry that was not a valid airplane")
            input_airId = input("Enter Airplane ID number: ")
        license_dict = self.mainObject.getAirplaneByIdLL(
            airplaneIdDict[input_airId])
        self.outputObject.singleAirplaneIdOH(license_dict)  # held

    '''inputObject.addNewAirplaneIH is called into newAirplane variable. (airplane object) is then passed
    down into logic layer through MainLL'''

    def registerAirplaneUI(self):
        newAirplane = self.inputObject.addNewAirplaneIH(
        )  # calls the input-handler for registering airplanes
        self.mainObject.addAirplaneLL(newAirplane)
        print("\nNew airplane saved!")
        input("Press any key to continue.")

    '''User inputs date and time which is then passed into getAirplaneStatusLL. Return value is dictionary with
       airplane ID as key and status as value. Dictionary then passed into outputObject where the information is printed'''

    def airplaneStatusUI(self):
        flagDate = True
        flagTime = True
        while flagDate:
            date = input('Enter date "YYYY-MM-DD": ')
            if self.errorObject.errorCheckDateEH(date):
                flagDate = False
            else:
                continue
        while flagTime:
            time = input('Enter time "HH:MM": ')
            if self.errorObject.errorCheckTimeEH(time):
                flagTime = False
            else:
                continue
        airplaneStatus_dict = self.mainObject.getAirplaneStatusLL(date, time)
        self.outputObject.airplaneStatusOH(airplaneStatus_dict)

    '''List of all pilots (objects) called into variable. Dictionary created with number as key and staff object as value.
       All pilots are printed onto screen with outputhandler. Inputhandler function called into dataList and datalist is then
       passed down into logic layer.'''

    def addLicenseUI(self):
        pilotObject_dict = {}
        pilotObject_list = self.mainObject.getAllPilotsLL()
        for counter, pilot in enumerate(pilotObject_list):
            pilotObject_dict[str(counter)] = pilot
        self.outputObject.allPilotsLicenseOH(pilotObject_dict)
        dataList = self.inputObject.addLicenseIH(pilotObject_dict)
        return self.mainObject.addLicenseLL(dataList)

    '''getLicenseDictLL called into variable, passes variable into outputObject where information is printed'''

    def getLicenseDictUI(self):
        licenseObject_dict = self.mainObject.getLicenseDictLL()
        return self.outputObject.airplaneLicensedOH(licenseObject_dict)