def isAdmin(spreadsheet_app, access_control_spreadsheet_id, user_id):
        """Return True if the specified user id has administrator permissions."""
        # Discord IDs are in column A, the associated tab name is in column B, and if 'Admin' is in column C, then it's an admin.
        range_name = WorksheetUtils.safeWorksheetName(
            AdminUtils.USERS_TAB_NAME) + '!A:C'
        rows = None
        try:
            values = spreadsheet_app.values().get(
                spreadsheetId=access_control_spreadsheet_id,
                range=range_name).execute()
            rows = values.get('values', [])
            if not rows:
                raise Exception('')
        except:
            # pylint: disable=raise-missing-from
            raise ExposableException(
                'Spreadsheet misconfigured'
            )  # deliberately low on details as this is replying in Discord.

        for row in rows:
            if str(row[0]) == str(user_id):
                result = (len(row) > 2 and row[2]
                          and row[2].lower() == 'admin')
                print('Admin check for user {0}: {1}'.format(user_id, result))
                return result
        return False
    def findAssociatedTab(spreadsheetApp, access_control_spreadsheet_id,
                          user_id):
        """Return the symbolic name of the user, to which the specified user ID (such as a Discord snowflake ID) is bound.

        In the context of the WOTV bot, this is also the name of the user-specific tabs in any/all associated spreadsheets.
        If the ID can't be found, an exception is raised with a safe error message that can be shown publicly in Discord.
        """
        # Discord IDs are in column A, the associated tab name is in column B
        range_name = WorksheetUtils.safeWorksheetName(
            AdminUtils.USERS_TAB_NAME) + '!A:B'
        rows = None
        try:
            values = spreadsheetApp.values().get(
                spreadsheetId=access_control_spreadsheet_id,
                range=range_name).execute()
            rows = values.get('values', [])
            if not rows:
                raise Exception('')
        except:
            # pylint: disable=raise-missing-from
            raise ExposableException(
                'Spreadsheet misconfigured'
            )  # deliberately low on details as this is replying in Discord.

        for row in rows:
            if str(row[0]) == str(user_id):
                return row[1]
        raise ExposableException(
            'User with ID {0} is not configured, or is not allowed to access this data. Ask your guild administrator for assistance.'
            .format(user_id))
    def searchVisionCardsByAbility(self, user_name: str, user_id: str, search_text: str) -> [VisionCard]:
        """Search for and return all VisionCards matching the specified search text, for the given user. Returns an empty list if there are no matches.

        Set either the user name or the user ID, but not both. If the ID is set, the tab name for the lookup is done as an indirection through
        the access control spreadsheet to map the ID of the user to the correct tab. This is best for self-lookups, so that even if a user
        changes their own nickname, they are still reading their own data and not the data of, e.g., another user who has their old nickname.
        """
        if (user_name is not None) and (user_id is not None):
            print('internal error: both user_name and user_id specified. Specify one or the other, not both.')
            raise ExposableException('Internal error')
        if user_id is not None:
            user_name = AdminUtils.findAssociatedTab(self.spreadsheet_app, self.access_control_spreadsheet_id, user_id)
        party_ability_row_tuples = WorksheetUtils.fuzzyFindAllRows(
            self.spreadsheet_app, self.vision_card_spreadsheet_id, user_name, search_text, 'P', 2)
        bestowed_ability_row_tuples = WorksheetUtils.fuzzyFindAllRows(
            self.spreadsheet_app, self.vision_card_spreadsheet_id, user_name, search_text, 'Q', 2)
        if len(party_ability_row_tuples) == 0 and len(bestowed_ability_row_tuples) == 0:
            return []

        # Accumulate all the matching rows
        all_matching_row_numbers = set()
        for (row_number, _) in party_ability_row_tuples:
            all_matching_row_numbers.add(row_number)
        for (row_number, _) in bestowed_ability_row_tuples:
            all_matching_row_numbers.add(row_number)
        all_matching_row_numbers = sorted(all_matching_row_numbers)

        range_name = WorksheetUtils.safeWorksheetName(user_name) + '!B2:Q' # Fetch everything from below the header row, starting with the name
        result = self.spreadsheet_app.values().get(spreadsheetId=self.vision_card_spreadsheet_id, range=range_name).execute()
        all_rows = result.get('values', [])
        all_matching_vision_cards = []
        for row_number in all_matching_row_numbers:
            all_matching_vision_cards.append(self.__readVisionCardFromRawRow(all_rows[row_number - 1])) # -1 for the header row
        return all_matching_vision_cards
    def readVisionCardByName(self, user_name: str, user_id: str, vision_card_name: str) -> VisionCard:
        """Read and return a VisionCard containing the stats for the specified vision card name, for the given user.

        Set either the user name or the user ID, but not both. If the ID is set, the tab name for the lookup is done as an indirection through
        the access control spreadsheet to map the ID of the user to the correct tab. This is best for self-lookups, so that even if a user
        changes their own nickname, they are still reading their own data and not the data of, e.g., another user who has their old nickname.
        """
        if (user_name is not None) and (user_id is not None):
            print('internal error: both user_name and user_id specified. Specify one or the other, not both.')
            raise ExposableException('Internal error')
        if user_id is not None:
            user_name = AdminUtils.findAssociatedTab(self.spreadsheet_app, self.access_control_spreadsheet_id, user_id)
        row_number, _ = self.findVisionCardRow(user_name, vision_card_name)
        # We have the location. Get the value!
        range_name = WorksheetUtils.safeWorksheetName(user_name) + '!B' + str(row_number) + ':Q' + str(row_number)
        result = self.spreadsheet_app.values().get(spreadsheetId=self.vision_card_spreadsheet_id, range=range_name).execute()
        rows = result.get('values', [])
        if not rows:
            raise ExposableException('{0} is not tracking any data for vision card {1}'.format(user_name, vision_card_name))
        return self.__readVisionCardFromRawRow(rows[0])
    def readResonance(self, user_name: str, user_id: str, unit_name: str,
                      esper_name: str):
        """Read and return the esper resonance, pretty unit name, and pretty esper name for the given (unit, esper) tuple, for the given user.

        Set either the user name or the user ID, but not both. If the ID is set, the tab name for the resonance lookup is done the
        same way as setResonance - an indirection through the access control spreadsheet is used to map the ID of the user to the
        correct tab. This is best for self-lookups, so that even if a user changes their own nickname, they are still reading their own data
        and not the data of, e.g., another user who has their old nickname.
        """
        if (user_name is not None) and (user_id is not None):
            print(
                'internal error: both user_name and user_id specified. Specify one or the other, not both.'
            )
            raise ExposableException('Internal error')
        if user_id is not None:
            user_name = AdminUtils.findAssociatedTab(
                self.spreadsheet_app, self.access_control_spreadsheet_id,
                user_id)

        esper_column_A1, pretty_esper_name = self.findEsperColumn(
            self.esper_resonance_spreadsheet_id, user_name, esper_name)
        unit_row, pretty_unit_name = self.findUnitRow(
            self.esper_resonance_spreadsheet_id, user_name, unit_name)

        # We have the location. Get the value!
        range_name = WorksheetUtils.safeWorksheetName(
            user_name) + '!' + esper_column_A1 + str(
                unit_row) + ':' + esper_column_A1 + str(unit_row)
        result = self.spreadsheet_app.values().get(
            spreadsheetId=self.esper_resonance_spreadsheet_id,
            range=range_name).execute()
        final_rows = result.get('values', [])

        if not final_rows:
            raise ExposableException(
                '{0} is not tracking any resonance for esper {1} on unit {2}'.
                format(user_name, pretty_esper_name, pretty_unit_name))

        return final_rows[0][0], pretty_unit_name, pretty_esper_name
    def setResonance(self, user_id: str, unit_name: str, esper_name: str,
                     resonance_numeric_string: str, priority: str,
                     comment: str):
        """Set the esper resonance.

        Returns the old value, new value, pretty unit name, and pretty esper name for the given (unit, esper) tuple, for the given user.
        """
        resonance_int = None
        try:
            resonance_int = int(resonance_numeric_string)
        except:
            # pylint: disable=raise-missing-from
            raise ExposableException('Invalid resonance level: "{0}"'.format(
                resonance_numeric_string
            ))  # deliberately low on details as this is replying publicly.
        if (resonance_int < 0) or (resonance_int > 10):
            raise ExposableException(
                'Resonance must be a value in the range 0 - 10')

        user_name = AdminUtils.findAssociatedTab(
            self.spreadsheet_app, self.access_control_spreadsheet_id, user_id)

        esper_column_A1, pretty_esper_name = self.findEsperColumn(
            self.esper_resonance_spreadsheet_id, user_name, esper_name)
        unit_row, pretty_unit_name = self.findUnitRow(
            self.esper_resonance_spreadsheet_id, user_name, unit_name)

        spreadsheet = self.spreadsheet_app.get(
            spreadsheetId=self.esper_resonance_spreadsheet_id).execute()
        sheetId = None
        for sheet in spreadsheet['sheets']:
            sheetTitle = sheet['properties']['title']
            if sheetTitle == user_name:
                sheetId = sheet['properties']['sheetId']
                break
        if sheetId is None:
            raise ExposableException(
                'Internal error: sheet not found for {0}.'.format(user_name))

        # We have the location. Get the old value first.
        range_name = WorksheetUtils.safeWorksheetName(
            user_name) + '!' + esper_column_A1 + str(
                unit_row) + ':' + esper_column_A1 + str(unit_row)
        result = self.spreadsheet_app.values().get(
            spreadsheetId=self.esper_resonance_spreadsheet_id,
            range=range_name).execute()
        final_rows = result.get('values', [])
        old_value_string = '(not set)'
        if final_rows:
            old_value_string = final_rows[0][0]

        # Now that we have the old value, try to update the new value.
        # If priority is blank, leave the level (high/medium/low) alone.
        if priority is not None:
            priority = priority.lower()
        priorityString = None
        if resonance_int == 10:
            priorityString = '10/10'
        elif (priority == 'l') or (priority == 'low') or (
                priority is None and 'low' in old_value_string.lower()):
            priorityString = EsperResonanceManager.RESONANCE_LOW_PRIORITY_VALUE_TEMPLATE.format(
                resonance_int)
        elif (priority == 'm') or (priority == 'medium') or (
                priority is None and 'medium' in old_value_string.lower()):
            priorityString = EsperResonanceManager.RESONANCE_MEDIUM_PRIORITY_VALUE_TEMPLATE.format(
                resonance_int)
        elif (priority == 'h') or (priority == 'high') or (
                priority is None and 'high' in old_value_string.lower()):
            priorityString = EsperResonanceManager.RESONANCE_HIGH_PRIORITY_VALUE_TEMPLATE.format(
                resonance_int)
        elif priority is None:
            # Priority not specified, and old value doesn't have high/medium/low -> old value was blank, or old value was 10.
            # Default to low priority.
            priorityString = EsperResonanceManager.RESONANCE_LOW_PRIORITY_VALUE_TEMPLATE.format(
                resonance_int)
        else:
            raise ExposableException(
                'Unknown priority value. Priority should be blank or one of "L", "low", "M", "medium", "H", "high"'
            )

        allRequests = [
            WorksheetUtils.generateRequestToSetCellText(
                sheetId, unit_row, esper_column_A1, priorityString)
        ]
        if comment:
            comment_text = comment
            if comment == '<blank>':  # Allow clearing the comment
                comment_text = None
            allRequests.append(
                WorksheetUtils.generateRequestToSetCellComment(
                    sheetId, unit_row, esper_column_A1, comment_text))
        requestBody = {'requests': [allRequests]}
        # Execute the whole thing as a batch, atomically, so that there is no possibility of partial update.
        self.spreadsheet_app.batchUpdate(
            spreadsheetId=self.esper_resonance_spreadsheet_id,
            body=requestBody).execute()
        return old_value_string, priorityString, pretty_unit_name, pretty_esper_name
    def readResonanceList(self, user_name: str, user_id: str,
                          query_string: str):
        """Read and return the pretty name of the query subject (either a unit or an esper), and resonance list for the given user.

        Set either the user name or the user ID, but not both. If the ID is set, the tab name for the resonance lookup is done the
        same way as setResonance - an indirection through the access control spreadsheet is used to map the ID of the user to the
        correct tab. This is best for self-lookups, so that even if a user changes their own nickname, they are still reading their own data
        and not the data of, e.g., another user who has their old nickname.

        The returned list of resonances is either (unit/resonance) or (esper/resonance) tuples.
        """

        if (user_name is not None) and (user_id is not None):
            print(
                'internal error: both user_name and user_id specified. Specify one or the other, not both.'
            )
            raise ExposableException('Internal error')
        if user_id is not None:
            user_name = AdminUtils.findAssociatedTab(
                self.spreadsheet_app, self.access_control_spreadsheet_id,
                user_id)

        esper_column_A1 = None
        pretty_esper_name = None
        unit_row_index = None
        pretty_unit_name = None
        mode = None
        target_name = None

        # First try to look up a unit whose name matches.
        unit_lookup_exception_message = None
        try:
            unit_row_index, pretty_unit_name = self.findUnitRow(
                self.esper_resonance_spreadsheet_id, user_name, query_string)
            mode = 'for unit'
            target_name = pretty_unit_name
        except ExposableException as ex:
            unit_lookup_exception_message = ex.message

        # Try an esper lookup instead
        esper_lookup_exception_message = None
        if mode is None:
            try:
                esper_column_A1, pretty_esper_name = self.findEsperColumn(
                    self.esper_resonance_spreadsheet_id, user_name,
                    query_string)
                mode = 'for esper'
                target_name = pretty_esper_name
            except ExposableException as ex:
                esper_lookup_exception_message = ex.message

        # If neither esper or unit is found, fail now.
        if mode is None:
            raise ExposableException(
                'Unable to find a singular match for: ```{0}```\nUnit lookup results: {1}\nEsper lookup results: {2}'
                .format(query_string, unit_lookup_exception_message,
                        esper_lookup_exception_message))

        # Grab all the data in one call, so we can read everything at once and have atomicity guarantees.
        result = self.spreadsheet_app.values().get(
            spreadsheetId=self.esper_resonance_spreadsheet_id,
            range=WorksheetUtils.safeWorksheetName(user_name)).execute()
        result_rows = result.get('values', [])
        resonances = []
        if mode == 'for esper':
            esper_index = WorksheetUtils.fromA1(
                esper_column_A1) - 1  # 0-indexed in result
            rowCount = 0
            for row in result_rows:
                rowCount += 1
                if rowCount < 3:
                    # skip headers
                    continue
                # rows collapse to the left, so only the last non-empty column exists in the data
                if len(row) > esper_index:
                    # annnnd as a result, there might be a value to the right, while this column could be empty.
                    if row[esper_index]:
                        resonances.append(row[1] + ': ' + row[esper_index])
        else:  # mode == 'for unit'
            colCount = 0
            unit_row = result_rows[unit_row_index - 1]  # 0-indexed in result
            for column in unit_row:
                colCount += 1
                if colCount < 3:
                    # skip headers
                    continue
                if column:
                    # Grab the esper name from the top of this column, and then append the column value.
                    resonances.append(result_rows[1][colCount - 1] + ': ' +
                                      column)

        # Format the list nicely
        resultString = ''
        for resonance in resonances:
            resultString += resonance + '\n'
        resultString = resultString.strip()
        return (target_name, resultString)