#! /usr/bin/env python3

# taken from:
#    https://docs.python.org/3.4/howto/webservers.html

import cgi

# enable debugging.  Note that the Python docs recommend this for testing, but
# say that it's a very bad idea to leave enabled in production, as it can leak
# information about your internal implementation.
import cgitb
cgitb.enable(display=0, logdir="/var/log/httpd/cgi_err/")

import MySQLdb
import private_no_share_dangerous_passwords as pnsdp
SQL_DB = "oauth_experiments"

import json

import google.oauth2.credentials
from googleapiclient.discovery import build



class FormError(BaseException):
    def __init__(this, msg):
        this.msg = msg

def main():
    # get the username from the CGI variables

    form = cgi.FieldStorage()

    if "username" not in form:
        raise FormError("No username")
    username = form["username"].value

    # connect to the database

    conn = MySQLdb.connect(host   = pnsdp.SQL_HOST,
                           user   = pnsdp.SQL_USER,
                           passwd = pnsdp.SQL_PASSWD,
                           db     = SQL_DB)

    # look up the user in the database; read the current login state

    cursor = conn.cursor()
    cursor.execute("""SELECT auth_state,credentials FROM users WHERE username=%s;""", (username,))
    records = cursor.fetchall()
    cursor.close()

    if len(records) != 1 or records[0][0] != "":
        raise FormError("Invalid username or auth state")

    credentials = json.loads(records[0][1])
    if "token" not in credentials or "token_uri" not in credentials or "scopes" not in credentials:
        raise FormError("Invalid credentials in database")

    # convert the credentials (dictionary) into a Credentials object
    credentials = google.oauth2.credentials.Credentials(**credentials)

    # if we get here, then the username is valid, and it appears that we have
    # a token for them.  Use it to connect to Google Docs

    drive = build("drive","v2", credentials=credentials)

    print("Content-type: text/html")
    print()

    print("""<html>

<body>

""")

    files = drive.files().list().execute()

    for f in files["items"]:
        print("""<p><a href="details?username=%s&id=%s">%s</a>""" % (username, f["id"], f["title"]))

    print("</body></html>")


    
def print_r(obj, prefix=""):
    print(prefix+"TYPE: "+repr(type(obj)))

    if type(obj) == dict:
        for k in obj.keys():
            print(prefix+"  KEY: "+repr(k))
            print_r(obj[k], prefix+"    ")
            print()

    elif type(obj) == list:
        for i in range(len(obj)):
            print(prefix+"  [%d]: " % i)
            print_r(obj[i], prefix+"    ")
            print()

    elif type(obj) == str:
        print(prefix+"VAL : %s" % obj.encode("utf-8"))

    else:
        print(prefix+"VAL : "+repr(obj))



def report_error(msg):
    print("""<html>

<body>

<p>ERROR: %s

</body>
</html>

""" % msg, end="")



try:
    main()

except FormError as e:
    print("Content-type: text/html")
    print()
    report_error(e.msg)


