def rank(self, role: str, inputQuestion: str = ""):
        """Input for employee rank"""

        pilotRanks_list = [{"Pilot ranks": RANK_CAPTAIN}, {"Pilot ranks": RANK_COPILOT}]
        cabinRanks_list = [{"Cabin crew ranks": RANK_FSM}, {"Cabin crew ranks": RANK_FA}]

        if role == ROLE_PILOT:  #Ranks for the Pilots
            DisplayScreen().printOptions(pilotRanks_list, header = "")
            return InputHandler().multipleNumChoices(pilotRanks_list,inputQuestion)
        else:   #Ranks for the Cabin Crew
            DisplayScreen().printOptions(cabinRanks_list, header = "")
            return InputHandler().multipleNumChoices(cabinRanks_list,inputQuestion)
    def selectDepartureTime(self, questionDate: str, questionTime: str,
                            errorMessage: str):
        """Prompts the user to input date and time"""

        #ERROR Check if there is any departing from Iceland at this dateTime
        departingFlights_list = IOAPI().opener(
            self.dataFiles["UPCOMING_FLIGHTS_FILE"])
        departingOnDate_list = []

        selectedDate = InputHandler().dateOnly(questionDate)
        # just collect the flights departing on same day
        for flight in departingFlights_list:
            if flight['departingFrom'] == self.__departingFrom:
                if flight['departure'][:10] == selectedDate[:10]:
                    departingOnDate_list.append(flight)

        # print the list of flights departing on that day
        headerDepartingOnDate_str = "List of other flights departing on same day"
        if len(departingOnDate_list) == 0:
            DisplayScreen().printText(["No departing flights"],
                                      headerDepartingOnDate_str)
        else:
            DisplayScreen().printList(departingOnDate_list,
                                      headerDepartingOnDate_str)

        #ask the user for a time before entering the loop
        selectedDepartureTime_str = InputHandler().timeOnly(questionTime)
        while True:
            #check through list of flights and check their departure time
            if len(departingOnDate_list) != 0:
                for flight in departingOnDate_list:
                    flightDeparture = flight['departure']
                    timeCheckDate = DateUtil().updateTime(
                        selectedDate, selectedDepartureTime_str)

                    #if airport was occupied, then print the list again and ask for time input
                    if flightDeparture == timeCheckDate:
                        DisplayScreen().printList(
                            departingOnDate_list,
                            "Departure time not available, please try again")
                        selectedDepartureTime_str = InputHandler().timeOnly(
                            "Please select a different time, " + questionTime)
                        continue
                    else:
                        #if everything is alright, then return the dateTime
                        return timeCheckDate
            else:
                return DateUtil().updateTime(selectedDate,
                                             selectedDepartureTime_str)
Exemple #3
0
        def assignCrew(availableCrew_list: list, selectedRole_str: str,
                       flightPair: list):
            """Finds the crew to """
            currentVoyage = Voyage(flightPair)
            currentCrew = currentVoyage.addCrew()
            #get the available employees for current voyage

            roleList = {
                "captain": {
                    "rank": "Captain"
                },
                "copilot": {
                    "rank": "Copilot"
                },
                "fsm": {
                    "rank": "Flight Service Manager"
                },
                "fa1": {
                    "rank": "Flight Attendant"
                },
                "fa2": {
                    "rank": "Flight Attendant"
                },
            }

            # filter out only of right rank
            rankOnlyList = []
            for employee in availableCrew_list:
                if employee["rank"] == roleList[selectedRole_str]["rank"]:
                    rankOnlyList.append(employee)

            #ask what employee they wish to assign to role
            if len(availableCrew_list) != 0:
                DisplayScreen().printOptions(rankOnlyList)
                inputChoice = InputHandler().numChoices(
                    len(rankOnlyList), "Select an employee: ")
                selectedEmployee = rankOnlyList[int(inputChoice) - 1]
                currentCrew[selectedRole_str] = selectedEmployee["ssn"]
            else:
                DisplayScreen().printText(
                    ["No available crew for this role during this voyage"],
                    "Finding {} for voyage".format(
                        roleList[selectedRole_str]["rank"]))
                return flightPair
            #update the voyage info
            currentVoyage.addCrew(currentCrew)
            #get the flights with updated info
            newFlights = currentVoyage.getFlights()
            return newFlights
Exemple #4
0
    def getSingleEmployee(self):
        #fetches employee info
        filePackage = IOAPI().opener(self.dataFiles['CREW_FILE'])
        #asks for the SSN of the employee
        ssn_of_employee_str = InputHandler().ssn(
            "Enter the SSN of the employee you\'re looking for: ")
        #Validity check for SSN
        while ssn_of_employee_str == False:
            print("Invalid input")
            ssn_of_employee_str = InputHandler().ssn(
                "Enter the SSN of the employee you\'re looking for: ")

        #Check for if the SSN is in crew file
        ssn_in_file_bool = True
        list_to_print = []
        while ssn_in_file_bool:
            #goes through all the lines in the employee info
            for x in filePackage:
                #checks the SSN of the employee
                if x['ssn'] == ssn_of_employee_str:
                    list_to_print = [x]
            if list_to_print != []:
                ssn_in_file_bool = False
            else:
                print("No employee found with this SSN")
                ssn_of_employee_str = InputHandler().ssn(
                    "Enter the SSN of the employee you\'re looking for: ")

        return DisplayScreen().printList(list_to_print, "Chosen employee:")
Exemple #5
0
        def findVoyage(flightData: list):
            """Find the voyage"""
            #get the list
            departingFlights_list = []
            for flight in departingFlights_data:
                if flight['departingFrom'] == 'KEF':
                    departingFlights_list.append(flight)

            #give user option to choose how the list is sorted:
            sortOptions = [{
                "sortBy": "departure"
            }, {
                "sortBy": "arrivingAt"
            }, {
                "sortBy": "flightNumber"
            }]
            DisplayScreen().printOptions(sortOptions,
                                         header="Search for voyages from list")
            sortedChoice_int = int(InputHandler().numChoices(
                len(sortOptions),
                "How would you like the voyages to be sorted? :"))
            sortedBy_str = sortOptions[sortedChoice_int - 1]["sortBy"]

            #sort the list by departure time
            sortedDepartures_list = sorted(departingFlights_list,
                                           key=lambda i: i[sortedBy_str])

            #print the upcoming voyages
            DisplayScreen().printOptions(sortedDepartures_list)
            # ask user to select a flight from the list representing the voyage
            selectedFlight_int = int(InputHandler().numChoices(
                len(sortedDepartures_list), "Select a voyage from the list: "))
            selectedFlight_dict = sortedDepartures_list[selectedFlight_int - 1]

            # find the two connecting flights, by finding the index of selected flight
            flightIndex = departingFlights_data.index(selectedFlight_dict)
            return {
                "out": [flightIndex, departingFlights_data[flightIndex]],
                "in":
                [flightIndex + 1, departingFlights_data[flightIndex + 1]]
            }
Exemple #6
0
        def selectRoleForUpdate(flightPair: list):
            currentVoyage = Voyage(flightPair)
            rolesForUpdate_list = []
            for role, employee in currentVoyage.addCrew().items():
                #find the employee info, should find name
                crewInRole = {"role": role, "employee": employee}
                rolesForUpdate_list.append(crewInRole.copy())

            DisplayScreen().printOptions(rolesForUpdate_list,
                                         "Crew assigned to this voyage")
            selectedRole = InputHandler().numChoices(
                len(rolesForUpdate_list), "Select a role to update: ")
            return rolesForUpdate_list[int(selectedRole) - 1]["role"]
Exemple #7
0
    def createDestination(self):
        """Create destination. Get destinationLand, destinationAirport, destinationFlightTime, 
         destinationDistance, destinationContactPerson and destinationEmergencyPhone."""

        print("\nCreating new destination")
        destination_dict = {}

        self.destination = InputHandler().country(
            "Input the city where the new destination is located: ")

        # Airports
        # Get a list of dictionaties containing airports and destiations we currently fly to
        airport_data_list = IOAPI().opener(self.dataFiles["DESTINATIONS_FILE"])
        #Creates a list of airports NaN Air flyes to
        airport_list = []
        for a_line_dict in airport_data_list:
            airport_list.append(a_line_dict["id"])

        self.airport = InputHandler().airport(
            airport_list, "\nInput the ID (3 letters) of the new airport: ")
        self.flightTime = InputHandler().timeOnly(
            "\nInput the time it takes to fly to {} from Iceland (HH:MM): ".
            format(self.airport))
        self.distanceFromIceland = InputHandler().distance(
            "\nInput the distace from Iceland to {} (in km): ".format(
                self.airport))
        self.contactPerson = InputHandler().fullName(
            "\nInput the full name of the contact person for the new destination, {}: "
            .format(self.airport))
        self.emergencyPhone = InputHandler().phoneNumber(
            "\nInput the emergency phone number (7 digits) for the new destination, {}: "
            .format(self.airport))

        destination_dict["id"] = self.airport
        destination_dict["destination"] = self.destination
        destination_dict["flightDuration"] = self.flightTime
        destination_dict["distance"] = self.distanceFromIceland
        destination_dict["contactPerson"] = self.contactPerson
        destination_dict["emergencyPhone"] = self.emergencyPhone

        #Displays the input information and check if the user is happy with the info
        DisplayScreen().printList(
            [destination_dict],
            header="Creating new destination, check if info correct",
            frame=True)
        confirmation_bool = InputHandler().yesOrNoConfirmation(
            "Is this information correct (y/n)? ")
        if confirmation_bool:
            IOAPI().appender(self.dataFiles["DESTINATIONS_FILE"],
                             destination_dict)
Exemple #8
0
    def createPlane(self):
        """Method that creates new plane, requests input for planeName, and planeType. 
        Adds the plane to the registry"""

        plane_dict = {}

        #Takes in input for plane insignia and puts it under "planeInsignia" key in plane_dict
        plane_dict["planeInsignia"] = InputHandler().planeInsignia(
            "Input plane insignia (e.g. TF-XXX): ")

        #Creates a list of airplane types in the list
        airplane_data_list = IOAPI().opener(
            self.dataFiles["AIRCRAFT_TYPE_FILE"])
        airplaneType_list = []
        for a_line_dict in airplane_data_list:
            airplaneType_list.append(a_line_dict["planeTypeId"])
        #Turns the list into a list of dictionaries
        plane_list = []
        for x in airplaneType_list:
            planeType_dict = {}
            planeType_dict["Plane Type IDs: "] = x
            plane_list.append(planeType_dict)
        DisplayScreen().printOptions(plane_list, header="")
        #Input for plane Type ID
        plane_dict["planeTypeId"] = InputHandler().multipleNumChoices(
            plane_list, "Choose Plane Type ID: ")
        plane_dict["manufacturer"] = InputHandler().strNoCheck(
            "Input plane manufacturer: ")
        plane_dict["capacity"] = InputHandler().digit(
            "Input plane seating capacity: ")
        #Input confirmation
        DisplayScreen().printList([plane_dict], header="")
        confirmation_bool = InputHandler().yesOrNoConfirmation(
            "Is this information correct? (y/n)")
        if confirmation_bool:
            #Appending the input info to aircraft file
            IOAPI().appender(self.dataFiles["AIRCRAFT_FILE"], plane_dict)
    def license(self,role: str, aircraftType_list: list, inputQustion: str = ""):
        """Input for pilots licence. Returns a validated licence"""
        if role == ROLE_PILOT:
            plane_list = []
            for x in aircraftType_list:
                plane_dict = {}
                plane_dict["Licences"] = x
                plane_list.append(plane_dict)
                
            DisplayScreen().printOptions(plane_list, header = "")

            text_str = inputQustion
            return InputHandler().multipleNumChoices(plane_list, text_str)
        else:
            return "N/A"
    def selectAircraft(self):
        """Displays list of available aircrafts and selects one from input"""
        #Get and print list of available aircrafts
        aircrafts_list = IOAPI().opener(self.dataFiles["AIRCRAFT_FILE"])

        #needs to check if plane is actually available at selected timeframe
        available_planes = aircrafts_list

        # print the available aircrafts
        DisplayScreen().printOptions(available_planes, "planes")

        # Select a aircraft from list
        inputAircraft_str = "Enter the number of the plane you want to use in this voyage from the plane list: "
        selectedAircraft = InputHandler().numChoices(len(available_planes),
                                                     inputAircraft_str)
        self.__aircraftID = available_planes[int(selectedAircraft) -
                                             1]["planeInsignia"]
Exemple #11
0
    def role(self, inputQuestion: str = ""):
        """Input for employee role"""
        role_list = [{"Roles": ROLE_PILOT},{"Roles": ROLE_CC}]
        DisplayScreen().printOptions(role_list, header = "")
        #Asks for a single digit input to choose between roles
        role_str = self.numSetLength(1, inputQuestion)
        valid_options_list = ["1","2"] #These are valid inputs
        #Validity check for the input
        while role_str not in valid_options_list:
            print("Please choose a valid input")
            role_str = self.numSetLength(1, inputQuestion)
        
        #Changes the numbers into coresponding strings
        if role_str == "1":
            role_str = ROLE_PILOT
        else:
            role_str = ROLE_CC

        return role_str
    def createVoyage(self):
        '''Create a new voyage, voyage contains of two flights with different flight numbers.
            have to get destination that we already fly to, date that the voyage will occur and than when the flight back home to Iceland is '''

        # Get and print list of available destinations
        destination_list = IOAPI().opener(self.dataFiles["DESTINATIONS_FILE"])
        DisplayScreen().printOptions(destination_list, "destinations")

        # Seect a destination
        destination_str = InputHandler().numChoices(
            len(destination_list),
            "Select index of destination for this voyage: ")
        self.__destination = destination_list[int(destination_str) - 1]

        # Departure messages for inputHandler
        inputDepartureDate_str = "Enter departure date from Iceland to {} (DD/MM/YYYY): ".format(
            self.__destination["destination"])
        inputDepartureTime_str = "Enter departure time (HH:MM): "
        ErrorDepartureTime_str = "ERROR: Airport is occupied at selected time \nplease input a new departure time: "

        # get the departure time from inputHandler
        self.__departure = self.selectDepartureTime(inputDepartureDate_str,
                                                    inputDepartureTime_str,
                                                    ErrorDepartureTime_str)

        # Find a date and time for arrival

        departingDate_obj = DateUtil(self.__departure).createObject()
        flightDuration = self.__destination["flightDuration"].split(":")
        durationHours = flightDuration[0]
        durationMinutes = flightDuration[1]
        minReturnDate_obj = departingDate_obj + datetime.timedelta(
            hours=int(durationHours), minutes=int(durationMinutes))
        minReturnDate_util = DateUtil(minReturnDate_obj.isoformat())
        inputArrivalDate_str = "Enter return date to Iceland from {} (DD/MM/YYYY): ".format(
            self.__destination["destination"])
        inputArrivalTime_str = "Enter time for return (HH:MM): "

        while True:
            try:
                returnDate_str = InputHandler().dateTime(
                    inputArrivalDate_str, inputArrivalTime_str)
                returnDate_obj = DateUtil(returnDate_str).createObject()

                #return date/time needs to be greater than departure date/time
                if returnDate_obj > departingDate_obj:
                    #return needs to be at least departure + flightduration
                    if returnDate_obj >= minReturnDate_obj:
                        self.__return = returnDate_str
                        break
                    raise Exception
                else:
                    raise Exception
            except Exception:
                returnDate_str = "{}/{}/{}".format(minReturnDate_util.day,
                                                   minReturnDate_util.month,
                                                   minReturnDate_util.year)
                errorMessage_list = [
                    "Return needs to be at least {}h and {}m after departure".
                    format(durationHours, durationMinutes),
                    "That would be at least {} and {}".format(
                        returnDate_str, minReturnDate_util.time)
                ]
                DisplayScreen().printText(
                    errorMessage_list,
                    "Choose a date and time for return flight from {}".format(
                        self.__destination["destination"]))

        # Find available aircraft
        self.selectAircraft()

        # print all the info about the voyage for the user and ask if the info is correct, if not than edit info, else save to data

        # Make a flightnumber for both flights, the flight numbers are different depending on the destination and how many other flights have gone to the destination on this same day
        self.createFlights()
Exemple #13
0
    def createEmployee(self):
        """Assigns and holds onto the values given by input handler until all 
        information is fullfilled. Asks for confirmation. Turns the information
        into dict format and returns it #Should also write it into data"""

        employee_dict = {}

        #Personal information
        name_str = InputHandler().fullName("Input full name: ")
        ssn_str = InputHandler().ssn("Input SSN: ")
        address_str = InputHandler().address("Input address: ")
        phonenumber_str = InputHandler().phoneNumber(
            "Input a 7-digit phone number:")
        email_str = InputHandler().email("Input e-mail address: ")
        #Role

        role_str = InputHandler().role("Choose role: ")

        #Rank
        rank_str = InputHandler().rank(role_str, "Choose rank: ")

        #License
        #Gets a list of dictionaries containing aircraft type specifications
        airplane_data_list = IOAPI().opener(
            self.dataFiles["AIRCRAFT_TYPE_FILE"])
        #Creates a list of airplane types in the list
        airplaneType_list = []
        for a_line_dict in airplane_data_list:
            airplaneType_list.append(a_line_dict["planeTypeId"])

        #Gets input for license if relevant, sets to "N/A" if role = Cabin Crew
        license_str = InputHandler().license(role_str, airplaneType_list,
                                             "Choose license: ")

        #Turns the inputs into a dict
        employee_dict["ssn"] = ssn_str
        employee_dict["name"] = name_str
        employee_dict["role"] = role_str
        employee_dict["rank"] = rank_str
        employee_dict["licence"] = license_str
        employee_dict["address"] = address_str
        employee_dict["phonenumber"] = phonenumber_str
        employee_dict["email"] = email_str

        #Displays the input information
        DisplayScreen().printList([employee_dict], header="Employee info: ")
        #Asks for confirmation. If negative starts the editing process
        if InputHandler().yesOrNoConfirmation(
                "Is this information correct? (y/n): "):
            edit_bool = False
        else:
            edit_bool = True

        #Runs editing as long as the user confirmation is negative
        while edit_bool:
            #Creates a list of editing options
            options_list = [{
                "Edit choices:": "SSN"
            }, {
                "Edit choices:": "Name"
            }, {
                "Edit choices:": "Role"
            }, {
                "Edit choices:": "Rank"
            }, {
                "Edit choices:": "Licence"
            }, {
                "Edit choices:": "Address"
            }, {
                "Edit choices:": "Phone"
            }, {
                "Edit choices:": "Email"
            }]
            #Prints the beforementioned list of options
            DisplayScreen().printOptions(options_list, header="")
            #Asks user to choose what he wants to edit
            choice_str = InputHandler().multipleNumChoices(
                options_list, "Choose data to edit: ")

            if choice_str == "SSN":
                employee_dict[choice_str.lower()] = InputHandler().ssn(
                    "Input SSN: ")
            elif choice_str == "Name":
                employee_dict[choice_str.lower()] = InputHandler().fullName(
                    "Input full name: ")
            elif choice_str == "Address":
                employee_dict[choice_str.lower()] = InputHandler().address(
                    "Input address: ")
            elif choice_str == "Phone":
                employee_dict["phonenumber"] = InputHandler().phoneNumber(
                    "Input a 7-digit phone number: ")
            elif choice_str == "Email":
                employee_dict[choice_str.lower()] = InputHandler().email(
                    "Input e-mail address: ")
            elif choice_str == "Role":
                employee_dict["role"], employee_dict["rank"], employee_dict[
                    "licence"] = InputHandler().roleUpdate(airplaneType_list)
            elif choice_str == "Rank":
                employee_dict[choice_str.lower()] = InputHandler().rank(
                    employee_dict["role"], "Choose rank: ")
            elif choice_str == "Licence":
                employee_dict[choice_str.lower()] = InputHandler().license(
                    employee_dict["role"], airplaneType_list,
                    "Input licence: ")

            #Prints the results of editing and asks for confirmation
            DisplayScreen().printList([employee_dict],
                                      header="Employee info: ",
                                      frame=True)
            if InputHandler().yesOrNoConfirmation(
                    "Is this information correct? (y/n): "):
                edit_bool = False

        #Adds the employee to the crew file
        IOAPI().appender(self.dataFiles["CREW_FILE"], employee_dict)
        #Sorts the crew file alphabetically by name
        crewPackage = IOAPI().opener(self.dataFiles["CREW_FILE"])
        crewPackage = sorted(crewPackage, key=lambda i: i["name"])
        IOAPI().updater(self.dataFiles["CREW_FILE"], crewPackage)
Exemple #14
0
 def printData(self, data: list, header: str):
     if len(data) != 0:
         DisplayScreen().printList(data, header)
     else:
         DisplayScreen().printText([""], header)
     return InputHandler().confirmation("Press enter to continue...")
Exemple #15
0
    def updateEmployee(self):
        """choose a employee (get a list and choose from the list). Get the info about the chosen 
        employee and then choose what info you want to change. 
        Then the user will be asked if he wants to save the changes. 
        Save the new information about the employee to the list about all employees """

        #Show list
        GetLogic(self.dataFiles).getAllCrew()
        #Choose Employee
        #Show employee info
        #Ask what the m**********r wants to change for f***s sake
        #Change some shit or f**k off
        #Confirm whether the f****r is co ntent with the f*****g changes
        #f**k the f**k off

        #Show employee info
        filePackage = IOAPI().opener(self.dataFiles["CREW_FILE"])
        #asks for the SSN of the employee
        ssn_of_employee_str = InputHandler().ssn(
            "Enter the SSN of the employee you\'re looking for: ")

        #Sets it to True so that the while runs at least once
        employee_in_file_bool = True
        employee_info_list = []
        #goes through all the lines in the employee info
        while employee_in_file_bool:
            for x in filePackage:
                #checks the SSN of the employee
                if x['ssn'] == ssn_of_employee_str:
                    employee_index = filePackage.index(x)
                    employee_info_dict = x
                    employee_info_list = [x]
            if employee_info_list != []:
                employee_in_file_bool = False
            else:
                print("Employee not found!")
                ssn_of_employee_str = InputHandler().ssn(
                    "Enter the SSN of the employee you\'re looking for: ")

        DisplayScreen().printList(employee_info_list,
                                  "Chosen employee:",
                                  frame=True)

        #Creates a list of editing options
        options_list = [{
            "Edit choices:": "Role"
        }, {
            "Edit choices:": "Rank"
        }, {
            "Edit choices:": "License"
        }, {
            "Edit choices:": "Address"
        }, {
            "Edit choices:": "Phone"
        }, {
            "Edit choices:": "Email"
        }]
        #Prints the beforementioned list of options
        DisplayScreen().printOptions(options_list, header="")
        #Asks user to choose what he wants to edit
        choice_str = InputHandler().multipleNumChoices(
            options_list, "Choose data to update: ")

        #Creates a list of airplane types
        airplane_data_list = IOAPI().opener(
            self.dataFiles["AIRCRAFT_TYPE_FILE"])
        airplaneType_list = []
        for a_line_dict in airplane_data_list:
            airplaneType_list.append(a_line_dict["planeTypeId"])

        #Changes the requested data
        if choice_str == "Address":
            employee_info_dict[choice_str.lower()] = InputHandler().address(
                "Input address: ")
        elif choice_str == "Phone":
            employee_info_dict["phonenumber"] = InputHandler().phoneNumber(
                "Input a 7-digit phone number: ")
        elif choice_str == "Email":
            employee_info_dict[choice_str.lower()] = InputHandler().email(
                "Input e-mail address: ")
        elif choice_str == "Role":
            employee_info_dict["role"], employee_info_dict[
                "rank"], employee_info_dict["licence"] = InputHandler(
                ).roleUpdate(airplaneType_list)
        elif choice_str == "Rank":
            employee_info_dict[choice_str.lower()] = InputHandler().rank(
                employee_info_dict["role"], "Choose rank: ")
        elif choice_str == "Licence":
            employee_info_dict[choice_str.lower()] = InputHandler().license(
                employee_info_dict["role"], airplaneType_list,
                "Input licence: ")

        #Prints the data and asks for confirmation
        DisplayScreen().printList([employee_info_dict], header="")
        continue_bool = InputHandler().yesOrNoConfirmation(
            "Do you want to change anything else? (y/n): ")
        while continue_bool:
            #Prints out editing options
            DisplayScreen().printOptions(options_list, header="")
            #Asks to choose what the user wants to edit
            choice_str = InputHandler().multipleNumChoices(
                options_list, "Choose data to update: ")

            #Changes the requested data
            if choice_str == "Address":
                employee_info_dict[choice_str.lower()] = InputHandler(
                ).address("Input address: ")
            elif choice_str == "Phone":
                employee_info_dict["phonenumber"] = InputHandler().phoneNumber(
                    "Input a 7-digit phone number: ")
            elif choice_str == "Email":
                employee_info_dict[choice_str.lower()] = InputHandler().email(
                    "Input e-mail address: ")
            elif choice_str == "Role":
                employee_info_dict["role"], employee_info_dict[
                    "rank"], employee_info_dict["licence"] = InputHandler(
                    ).roleUpdate(airplaneType_list)
            elif choice_str == "Rank":
                employee_info_dict[choice_str.lower()] = InputHandler().rank(
                    employee_info_dict["role"], "Choose rank: ")
            elif choice_str == "Licence":
                employee_info_dict[
                    choice_str.lower()] = InputHandler().license(
                        employee_info_dict["role"], airplaneType_list,
                        "Input licence: ")

            #Prints the results of editing and asks for confirmation
            DisplayScreen().printList([employee_info_dict], header="")
            continue_bool = InputHandler().yesOrNoConfirmation(
                "Do you want to change anything else? (y/n): ")
        else:
            if InputHandler().yesOrNoConfirmation(
                    "Do you want to save the changes? (y/n): "):
                #Updates the Crew file with the edited employee info
                filePackage[employee_index] = employee_info_dict
                IOAPI().updater(self.dataFiles["CREW_FILE"], filePackage)
                print("Data has been updated")
Exemple #16
0
    def updateDestination(self):
        """The user chooses a destination (get a list of all the destinations and then choose the airport id fromt the list). Get the info
        about the chosen destination and then choose what info the user wnat to change.
        Then the user will be asked if he wants to save the changes.
        Save the new info about the destination to the list of all destinations. (if the user does not want to save then the old info about
        the destination will be kept in the list of all destinations)"""

        #get and show the user the list of all destinations
        GetLogic(self.dataFiles).getDestinations()
        #choose a destination the user wants to change
        #GetLogic(self.dataFiles).getOneDestination()

        #fetches destinations info
        filePackage = IOAPI().opener(self.dataFiles['DESTINATIONS_FILE'])

        #Creates a list of airports NaN Air flyes to
        airport_list = []
        for a_line_dict in filePackage:
            airport_list.append(a_line_dict["id"])

        #asks for the ID of the destination
        id_of_destination_str = InputHandler().destinationID(
            airport_list, "Enter the ID of the airport you want to change: ")

        #Set id_in_file_bool to True so that the while runs at least once
        id_in_file_bool = True
        airport_info_list = []
        #goes through all the lines in the destination info
        while id_in_file_bool:
            for x in filePackage:
                #checks the ID of the destinations
                airport_index = filePackage.index(x)
                if x["id"] == id_of_destination_str:
                    airport_info_dict = x
                    airport_info_list = [x]
            if airport_info_list != []:
                id_in_file_bool = False
            else:
                print("Airport not found!")
                id_of_destination_str = InputHandler().destinationID(
                    airport_list,
                    "Enter the ID of the airport you want to change: ")

        DisplayScreen().printList(airport_info_list,
                                  "Chosen airport: ",
                                  frame=True)

        #creates a list of editing optins
        options_list = [{
            "Edit choices:": "Contact Person"
        }, {
            "Edit choices:": "Emergency number"
        }]
        #Prints the before mentioned list of options
        DisplayScreen().printOptions(options_list, header="")
        #Asks the user to choose what he/she wants to edit
        choice_str = InputHandler().multipleNumChoices(
            options_list, "Choose data you want to update: ")

        #Changes the requested data
        if choice_str == "Contact Person":
            airport_info_dict["contactPerson"] = InputHandler().fullName(
                "Enter the name of the new contact person: ")

        elif choice_str == "Emergency number":
            airport_info_dict["emergencyPhone"] = InputHandler().phoneNumber(
                "Input a 7 digit phone number for the new emergency phone number: "
            )

        #Prints the data and asks for confirmation
        DisplayScreen().printList([airport_info_dict], header="")
        continue_bool = InputHandler().yesOrNoConfirmation(
            "Do you want to change anything else? (y/n): ")

        while continue_bool:
            #Prints out editing options again
            DisplayScreen().printOptions(options_list, header="")
            #Asks the user to choose what he/she wants to edit
            choice_str = InputHandler().multipleNumChoices(
                options_list, "Choose data you want to update: ")

            #Changes the requested data
            if choice_str == "Contact Person":
                airport_info_dict["contactPerson"] = InputHandler.fullName(
                    "Enter the name of the new contact person: ")

            elif choice_str == "Emergency number":
                airport_info_dict["emergencyPhone"] = InputHandler.phoneNumber(
                    "Input a 7 digit phone number for the new emergency phone number: "
                )

            #Prints the results of editing and asks for confirmation
            DisplayScreen().printList([airport_info_dict], header="")
            continue_bool = InputHandler().yesOrNoConfirmation(
                "Do you want to change anything else? (y/n): ")

        else:
            #Updates the Destination file with the edited destion info
            filePackage[airport_index] = airport_info_dict
            IOAPI().updater(self.dataFiles["DESTINATIONS_FILE"], filePackage)
            print("Data has been updated")