import csv


def get_session_list(cfg) -> list:
    """
    Build a list of all the sessions (identified by row numbers where the session starts),
    as detected in the user data log. A new session is started whenever the session time
    goes backwards, or the first row is read.
    :param cfg: configuration object
    :return: list of CSV rows were a new session was detected
    """
    print('Building session list...')

    session_list = list()

    csv_row_index = 0

    # read a CSV file as a dictionary
    with open(cfg.csv_input_filename, newline='') as csv_file:
        csv_reader = csv.DictReader(csv_file)

        last_session_time = -1.0

        for csv_row in csv_reader:
            # read the session times
            session_time = csv_row['Session Time']

            # continue if the session time is blank
            if not session_time:
                continue

            # convert it to a number
            session_time = float(session_time)

            # if this is the first session or the session time went backwards,
            # it must be a new session
            if (csv_row_index == 0) or (session_time < last_session_time):
                session_list.append(csv_row_index)

            last_session_time = session_time
            csv_row_index += 1

        # add a final entry at the end so consumers know when to stop
        # this final entry does not mark the start of a new session
        session_list.append(csv_row_index)

    # don't count the last, since it isn't really a session
    session_count = len(session_list) - 1
    print('Found {} sessions!'.format(session_count))

    return session_list