# -*- coding: utf-8 -*-
#
# Copyright 2016 Continuum Analytics, Inc.
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
#

"""
"""

# Standard library imports
import json
import re
import subprocess

try: # PY3
    from urllib.request import urlopen
except ImportError: # PY2
    from urllib2 import urlopen


def find_all_apps():
    """
    Find all apps in all channels. No caching of repodata.
    """
    cmd = ['conda', 'info']
    out = subprocess.check_output(cmd)
    reg = re.compile(b' http.*?\n')
    channels = reg.findall(out)
    channels = [c[1:-1].decode() for c in channels]
    channels = {c.rsplit('/', 2)[0] for c in channels}
    tail = 'repodata.json'
    out = {}

    for channel in channels:
        urli = channel[1:-1].decode()
        url = '{0}{1}'.format(urli, tail)
        print(url)
        try:
            dic = json.loads(urlopen(url).read().decode())
            out[urli] = set(d['name'] for d in dic['packages'].values()
                            if 'app' in d.get('type', ''))
        except Exception as e:
            print(e)
    return out
