# -*- coding: utf-8 -*-


from flask import Flask, render_template, request
app = Flask(__name__)

import requests

onionoo_endpoint = {
    "bandwidth": "https://onionoo.torproject.org/bandwidth",
    "details": "https://onionoo.torproject.org/details",
}

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/eligibility/<fingerprint>')
def eligibility_by_keyword(fingerprint):
    return tshirt_eligibility(fingerprint)

@app.route('/eligibility')
def eligibility_by_param():
    fingerprint = request.args.get('fingerprint', '')
    return tshirt_eligibility(fingerprint)

def tshirt_eligibility(fingerprint):
    try:
        bandwidth_document = requests.get(ONIONOO_ENDPOINT["bandwidth"], params={"lookup": fingerprint}).json()
        details_document = requests.get(ONIONOO_ENDPOINT["details"], params={"lookup": fingerprint}).json()
    except requests.exceptions.RequestException, exc:
        app.logger.error(str(exc))
        return render_template("error.html", onionoo_down = True), 500
    
    if len(bandwidth_document["relays"]) == 0 or len(details_response["relays"]) == 0:
        return render_template("error.html", not_relay = True)
    
    write_history_3_months = bandwidth_document["relays"][0]["write_history"]["3_months"]
    months_3 = write_history_3_months["values"]
    interval = int(write_history_3_months["interval"])
    factor = int(write_history_3_months["factor"])
    excess_seconds = (len(months_3) * interval) - 5270400 # 2 months => 61 days => 61 * 24 * 60 * 60

    if excess_seconds >= 0:
        excess_values = excess_seconds / interval
        months_2 = [int(val) for val in filter(None, months_3[excess_values:])]
    else:
        return render_template("error.html", insufficient_data = True), 500
    average_bandwidth = (factor * sum(months_2))/len(months_2)

    if parse_exit80(details_document['relays'][0]['exit_policy_summary']):
        return render_template("eligibility.html", eligible = (average_bandwidth > 102400))
    else:
        return render_template("eligibility.html", eligible = (average_bandwidth > 512000))

def parse_exit_policy_entry(entry):
    """port or startport-endport"""
    if "-" in entry:
        return map(int, entry.split("-"))
    else:
        return int(entry)

def check_contains_80(item):
    if type(item) == list:
        return item[0] <= 80 <= item[1]
    else:
        return item == 80

def allow_exit80(exit_policy_summary):
    if "accept" in exit_policy_summary:
        key = "accept"
    elif "reject" in exit_policy_summary:
        key = "reject"

    return len([policy_item for policy_item in exit_policy_summary[key] if check_contains_80(parse_exit_policy_entry(policy_item))]) > 0

if __name__ == "__main__":
    app.run(debug = True)
