###################################################################################
# LAVA QA tool - Utility API module.
# Copyright (C) 2016 Collabora Ltd.

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  US
###################################################################################

class RangeNotationError(Exception):
    pass

def job_id_list_from_range(jobs_range):
    """This function builds a job id list from a range of jobs ids.

    Many of the commands accept job id's as arguments, these can be given
    individually 'Id0 Id1 .. IdN' or with a range notation like 'Id0-IdN',
    or even a combination of both notations 'Id0 Id0-IdN Id1 Id1-IdN Id3'.

    This function takes into consideration such a special notation and
    generates a proper list of id's (of integer type) that can be later easily
    used by each of the commands, so this function also converts the job id's 
    from string type (as received by argparser) to an integer type."""

    job_ids_list = []
    try:
        for job_id in jobs_range:
            job_ids = job_id.split('-', 2)
            n = len(job_ids)
            if n == 1:
                job_ids_list.append(int(job_ids[0]))
            elif n == 2:
                # If job_id_value is == 2 then it is a range.
                frm, to = int(job_ids[0]), int(job_ids[1])
                if frm > to:
                    # Go backward if from > to.
                    job_ids_list.extend(range(frm, to - 1, -1))
                else:
                    job_ids_list.extend(range(frm, to + 1))
            else:
                raise RangeNotationError("job range error: not a valid range: {}"
                                         .format(job_ids))
    # Catch all the exceptions and raise them as RangeNotationError
    except Exception as e:
        raise RangeNotationError("job range error: {}".format(e))

    return job_ids_list
