from collections import Counter
from flask import abort, jsonify, request, url_for
from . import APP
from .helpers import get_current_version, record_check
from .models import Installation, Package


ALLOWED_PACKAGES = {'lazysusan', 'praw'}


@APP.route('/')
def home():
    return "Hello!"


@APP.route('/check', methods=['PUT'])
def check():
    if 'python-requests' not in request.headers.get('User-Agent', ''):
        abort(403)
    required = set(('package_name', 'package_version', 'platform',
                   'python_version'))

    if not request.json or not required.issubset(request.json):
        abort(400)

    package_name = request.json['package_name']
    if package_name not in ALLOWED_PACKAGES:
        abort(400)

    record_check(package_name, request.json['package_version'],
                 request.json['platform'], request.json['python_version'],
                 request.remote_addr)

    return jsonify(get_current_version(package_name))


@APP.route('/list')
def list():
    retval = '<ul>\n'
    packages = Counter(x.package_name for x in Package.query.all())
    for package, count in sorted(packages.items()):
        retval += ('  <li><a href="{2}">{0}</a> ({1} versions)</li>\n'
                   .format(package, count, url_for('package_info',
                                                   package_name=package)))
    return retval + '<ul>\n'


@APP.route('/p/<package_name>')
def package_info(package_name):
    packages = Package.query.filter_by(package_name=package_name).all()
    by_id = {x.id: x for x in packages}
    results = Installation.recent_counts(Installation.package_id,
                                         [x.id for x in packages])

    rows = ['<tr><th>Version</th><th>Unique</th><th>Total</th></tr>']
    for pid, uniq, total in results:
        rows.append('<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>'
                    .format(str(by_id[pid]), uniq, total))
    return '<h3>Versions from the last 24 hours</h3>\n<table>\n{0}</table>'\
        .format('\n'.join(rows))

@@ -1011,16 +1011,35 @@
 val = '%3C
+h3%3EPackages%3C/h3%3E%5Cn%3C
 ul%3E%5Cn'%0A 
@@ -1392,21 +1392,68 @@
 val + '%3C
+/
 ul%3E%5Cn
+%3Cp%3E%3Ca href=%22/python%22%3EPython Versions%3C/a%3E%3C/p%3E%5Cn
 '%0A%0A%0A@APP
@@ -1828,16 +1828,45 @@
 %3C/tr%3E'%5D%0A
+    uniq_sum = total_sum = 0%0A
     for 
@@ -2021,16 +2021,180 @@
 total))%0A
+        uniq_sum += uniq%0A        total_sum += total%0A%0A    rows.append('%3Ctr%3E%3Ctd%3ESum%3C/td%3E%3Ctd%3E%7B0%7D%3C/td%3E%3Ctd%3E%7B1%7D%3C/td%3E%3C/tr%3E'%0A                .format(uniq_sum, total_sum))%0A%0A
     retu
@@ -2295,8 +2295,69 @@
 (rows))%0A
+%0A%0A@APP.route('/python')%0Adef python_versions():%0A    return ''%0A

Add sum column to package versions.