from launchpadlib.launchpad import Launchpad
from collections import defaultdict

class PackageVersionHistory:
"""
Use launchpadlib api to query for the package history tree
of a target source_package_name + distro_series
"""
    def __init__(self, name, distro_series):
        self.name = name
        self.distro_series = distro_series
        self.launchpad = self.login()

    def login(self):
        return Launchpad.login_anonymously('package_version_history_lookup', 'production')

    def set_ubuntu(self):
        return self.launchpad.distributions['ubuntu']

    def set_distro_series(self):
        ubuntu = self.set_ubuntu()
        return ubuntu.getSeries(name_or_version=self.distro_series)

    def set_archive(self):
        ubuntu = self.set_ubuntu()
        return ubuntu.main_archive

    def get_published_sources(self):
        archive = self.set_archive()
        series = self.set_distro_series()
        return archive.getPublishedSources(source_name=self.name, distro_series=series)

    def package_name_and_version_history(self):
        sources = self.get_published_sources()
        results = []
        for source in sources:
            name = source.source_package_name
            version = source.source_package_version
            results.append((name, version))

        d = defaultdict(list)
        for k, v in results:
            d[k].append(v)

        return sorted(d.items())
