import logging


def update_softwaretitle_packages(api, jssid, pkgs):
    """
    Update packages of software title

    :param jssid:        Patch Software Title ID
    :param pkgs:         dict of {version: package, ...}

    :returns: None
    """
    logger = logging.getLogger(__name__)

    data = api.get(f"patchsoftwaretitles/id/{jssid}")
    title = data['patch_software_title']

    title_name = title['name']
    logger.info(f"updating patch software title: {title_name} ({jssid})")

    # single version (dict), multiple versions (list)
    version = title['versions']['version']
    _modified = False
    try:
        # access key of single version and count on TypeError being raised
        v = version['software_version']
        if v in pkgs.keys():
            version['package'] = {'name': pkgs[v]}
            _modified = True

    except TypeError:
        # looks like it was actually a list
        for _version in version:
            v = _version['software_version']
            if v in pkgs.keys():
                _version['package'] = {'name': pkgs[v]}
                _modified = True

    if _modified:
        result = api.put(f"patchsoftwaretitles/id/{jssid}", data)
        logger.info(f"succesfully updated: {title_name}")
        return result
    else:
        logger.info(f"software title was not modified")