from catalog import db
from catalog.models import User, Category, Item
from datetime import datetime
# Create All Tables
print "Creating tables ..."
db.create_all()

# Create First User
print "Creating User ..."
user = User()
user.username = "******"
user.email = "*****@*****.**"
user.gplus_id = '112241070706889739015'
user.created = datetime.utcnow()
user.modified = datetime.utcnow()
db.session.add(user)
db.session.commit()
print "User - Sophie Reddimalla created ID=" + str(user.id)

print "Creating Sample Category Football ..."
category = Category()
category.title = "Football"
category.user_id = user.id
category.created = datetime.utcnow()
category.modified = datetime.utcnow()
db.session.add(category)
db.session.commit()
print "Category - Football created ID=" + str(category.id)

print "Creating Sample Items in Football ..."
item = Item()
def gconnect():
    """
    Gathers data from Google Sign In API and places it inside a session variable.
    """
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets(
            '/var/www/catalog/catalog/client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        flash('Failed to upgrade the authorization code.')
        return (url_for('welcome'))


# Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(
            json.dumps('Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += '" style = "width: 300px; height:300px;border-radius: 150px;"> '
    flash("you are now logged in as %s" % login_session['username'])

    # Store this User in Database if not existing
    user = User.query.filter_by(gplus_id=str(gplus_id)).first()
    if user is None:
        user = User()
        user.username = login_session['username']
        user.email = login_session['email']
        user.gplus_id = str(login_session['gplus_id'])
        user.created = datetime.utcnow()
        user.modified = datetime.utcnow()
        db.session.add(user)
        db.session.commit()

    return output