# Copyright (C) 2012-2017 Craig Hobbs
#
# Licensed under the MIT License
# https://github.com/craigahobbs/chisel/blob/master/LICENSE

from collections import namedtuple
from urllib.parse import urlparse

from pip._internal.download import PipSession
from pip._internal.index import FormatControl, PackageFinder
from pip._internal.models.index import PyPI


DEFAULT_PIP_INDEX = PyPI.simple_url


IndexEntry = namedtuple('IndexEntry', (
    'name',
    'version',
    'filename',
    'hash',
    'hash_name',
    'url',
    'datetime'
))


PipPackage = namedtuple('PipPackageVersion', (
    'version',
    'link'
))


def pip_package_versions(index, package):
    format_control = FormatControl(no_binary=(':all:',), only_binary=())
    session = PipSession()
    finder = PackageFinder([], [index], format_control=format_control, session=session,
                           trusted_hosts=[urlparse(index).netloc.rsplit(':', 1)[0]])
    return sorted((PipPackage(str(pv.version), pv.location) for pv in finder.find_all_candidates(package)),
                  key=lambda pp: (pp.version, {'.tar.gz': 1, '.zip': 2, '.tar.bz2': 3}.get(pp.link.ext, 10000)))
