# Source code of the Ubuntu-it website
# Copyright (C) 2016  Pietro Albini <pietroalbini@ubuntu.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; witout even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import requests


BASE = "https://api.launchpad.net/devel"


def fetch_paginated(initial):
    """Fetch paginated data"""
    next_url = initial
    retry_count = 0
    while retry_count < 5:
        resp = requests.get(next_url)
        if resp.status_code == 200:
            retry_count = 0
            data = resp.json()
        else:
            retry_count += 1
            continue

        for entry in data["entries"]:
            yield entry

        if "next_collection_link" not in data:
            break
        next_url = data["next_collection_link"]

    if retry_count:
        raise RuntimeError("Failed to contact launchpad!")


def get_cdimage_mirrors(distro, country):
    """Get a list of cdimage mirrors"""
    result = []

    for mirror in fetch_paginated("%s/%s/cdimage_mirrors" % (BASE, distro)):
        # Ensure we get only CD Image mirrors
        if mirror["content"] != "CD Image":
            continue

        # Only get Official mirrors, please
        if mirror["status"] != "Official":
            continue

        # Only get mirrors of the specific country
        if not mirror["country_link"].endswith("/+countries/%s" % country):
            continue

        if mirror["http_base_url"] is None:
            continue

        url = mirror["http_base_url"]
        if url.endswith("/"):
            url = url[:-1]
        result.append(url)

    return result
