#!/usr/bin/env python3

import sys
import flask
import json
import psycopg2

app = flask.Flask(__name__)

database = 'butterfieldp'
user = 'butterfieldp'
password = 'carpet247chair'

try:
    connection = psycopg2.connect(database=database, user=user)
except Exception as e:
    print(e)
    exit()

#uery the database, leaving you with a "cursor"--an object you can
#use to iterate over the rows generated by your query.
try:
    cursor = connection.cursor()
except Exception as e:
    print(e)
    exit()

@app.route('/')
def hello():
    return 'Hello World'


@app.route('/candidates')
def get_candidates():
    fields = ['id', 'first_name', 'last_name', 'party', 'state', 'seat']
    return get_entity_data('candidates', fields) 

@app.route('/pacs')
def get_pacs():
    fields = ['id', 'name', 'industry_id', 'party', 'sensitive', 'international']
    return get_entity_data('pacs', fields)

@app.route('/industries')
def get_industries():
    fields = ['id', 'name']
    return get_entity_data('industries', fields)

@app.route('/individuals')
def get_individual_donors():
    fields = ['id', 'name', 'state', 'gender', 'industry_id']
    return get_entity_data('individual_donors', fields)

@app.route('/transactions')
def get_transactions():
    fields = ['date', 'amount', 'min_amount', 'max_amount', 'contributor_id', 'contributor_type', 'recipient_id', 'recipient_type']
    return get_entity_data('transactions', fields)

def get_entity_data(entities, fields):
    results = []
    query = "SELECT * from " + entities
    first = True
    params = {}
    for field in fields:
        params[field] = flask.request.args.get(field)
        if params[field] != None:
            if first:
                query += " WHERE "
                first = False
            else:
                query += " AND "
            if field not in ['min_amount', 'max_amount']:
                if ('name' not in field):
                    query += field +  " = %(" + field + ")s"
                else:
                    query += field +  " ILIKE %(" + field + ")s"
                    params[field] = "%%" + params[field] + "%%"
            elif (field is 'min_amount'):
                query += params[field] + '  <=  amount'
            else:
                query += params[field] + ' >= amount'
    print(cursor.mogrify(query, params))
    try:
        cursor.execute(query, params)
    except Exception as e:
        print(e)
        exit()
    for row in cursor:
        results.append(row)
    return json.dumps(results, default=str)

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('Usage: {0} host port'.format(sys.argv[0]))
        print('  Example: {0} perlman.mathcs.carleton.edu 5101'.format(sys.argv[0]))
        exit()

    host = sys.argv[1]
    port = int(sys.argv[2])
    app.run(host=host, port=port, debug=True)
