from stream.plugin import plugin

PUBLIC_TRACKERS = [
    "udp://tracker.publicbt.com:80/announce",
    "udp://tracker.openbittorrent.com:80/announce",
    "udp://open.demonii.com:1337/announce",
    "udp://tracker.istole.it:6969",
    "udp://tracker.coppersurfer.tk:80",
]


# Add default trackers to a magnet link, to improve its reachability
def _boost_magnet(magnet):
    from urllib import urlencode
    return "%s&%s" % (magnet, urlencode({"tr": PUBLIC_TRACKERS}, True))


def from_torrent_url(url):
    import base64
    import bencode
    import hashlib
    import urllib
    from stream.utils import url_get
    torrent_data = url_get(url)
    metadata = bencode.bdecode(torrent_data)
    hashcontents = bencode.bencode(metadata['info'])
    digest = hashlib.sha1(hashcontents).digest()
    b32hash = base64.b32encode(digest)
    params = {
        'dn': metadata['info']['name'],
        'tr': metadata['announce'],
    }
    plugin.log.info(params)
    paramstr = urllib.urlencode(params)
    return 'magnet:?%s&%s' % ('xt=urn:btih:%s' % b32hash, paramstr)


def ensure_magnet(uri):
    if not uri.startswith("magnet:"):
        uri = from_torrent_url(uri)
    return uri


def display_name(magnet_uri):
    import urlparse
    from stream.utils import first
    magnet_args = urlparse.parse_qs(magnet_uri.replace("magnet:?", ""))
    return first(magnet_args.get("dn", []))


@plugin.route("/play/<uri>")
def play(uri):
    from stream.player import TorrentPlayer
    if uri.startswith("magnet:") and plugin.get_setting("magnet_boost", bool):
        plugin.log.info("Enabled magnet booster")
        uri = _boost_magnet(uri)
    TorrentPlayer().init(uri).loop()
