from flask import Flask, render_template, request
from flask import redirect, jsonify, url_for, flash
from flask import make_response
from flask import session as login_session

from sqlalchemy import create_engine, asc
from sqlalchemy.orm import sessionmaker

from DatabaseSetup import Base, User, Car, CarOption

from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError

import httplib2
import json
import requests
import random
import string

app = Flask(__name__)


CLIENT_ID = json.loads(
    open('client_secrets.json', 'r').read())['web']['client_id']
APPLICATION_NAME = "UdacityCatalogProject"


# Connect to Database and create database session
engine = create_engine('sqlite:///DealershipInventory.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()


# Create anti-forgery state token
@app.route('/login')
def showLogin():
    state = ''.join(random.choice(string.ascii_uppercase + string.digits)
                    for x in xrange(32))
    login_session['state'] = state
#     # return "The current session state is %s" % login_session['state']
    return render_template('login.html', STATE=state)


@app.route('/gconnect', methods=['POST'])
def gconnect():
    # 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('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # 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)
        print "Token's client ID does not match app's."
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = 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'
        print stored_access_token
        print access_token
        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']


    # see if user exists, id not add a new entry
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    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: '
    output += '150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;">'
    flash("you are now logged in as %s" % login_session['username'])
    print "done!"
    return output


# DISCONNECT - Revoke a current user's token and reset their login_session
@app.route('/gdisconnect')
def gdisconnect():
    access_token = login_session.get('access_token')
    if access_token is None:
        print 'Access Token is None'
        response = make_response(json.dumps('Current user not connected.'),
                                 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    print 'In gdisconnect access token is %s', access_token
    print 'User name is: '
    print login_session['username']
    url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' \
        % login_session['access_token']
    h = httplib2.Http()
    result = h.request(url, 'GET')[0]
    print 'result is '
    print result
    if result['status'] == '200':
        del login_session['access_token']
        del login_session['gplus_id']
        del login_session['username']
        del login_session['email']
        del login_session['picture']
        response = make_response(json.dumps('Successfully disconnected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        flash("User Logoff Successful")
        return redirect(url_for('showCars'))
# return response
    else:
        response = make_response(json.dumps('Failed to revoke token for'
                                 'given user.', 400))
        response.headers['Content-Type'] = 'application/json'
        flash("User Logoff Failed")
        return redirect(url_for('showCars'))


def createUser(login_session):
    newUser = User(name=login_session['username'], email=login_session[
                   'email'], picture=login_session['picture'])
    session.add(newUser)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).one()
    return user.id


def getUserInfo(user_id):
    user = session.query(User).filter_by(id=user_id).one()
    return user


def getUserID(email):
    try:
        user = session.query(User).filter_by(email=email).one()
        return user.id
    except:
        return None


# JSON APIs
@app.route('/car/<int:car_id>/JSON')
def CarInfoJSON(car_id):
    car = session.query(Car).filter_by(id=car_id).one()
    items = session.query(CarOption).filter_by(
        car_id=car_id).all()

#   COULD NOT FIGURE OUT HOW TO SHOW BOTH THE CAR AND THE
#   OPTIONS AT THE SAME TIME
#   return jsonify(car.serialize)
    return jsonify(CarOption=[i.serialize for i in items])



@app.route('/car/<int:car_id>/options/JSON')
def CarOptionJSON(car_id):
    Car_Option = session.query(CarOption).filter_by(car_id=car_id).all()
    return jsonify(Car_Option=[i.serialize for i in Car_Option])


@app.route('/car/JSON')
def carsJSON():
    cars = session.query(Car).all()
    return jsonify(cars=[r.serialize for r in cars])


# Show all cars
@app.route('/')
@app.route('/car/')
def showCars():
    cars_table = session.query(Car).order_by(asc(Car.brand))
    return render_template('cars.html', cars_table=cars_table,
                           login_session=login_session)


# Create a new cars
@app.route('/car/new/', methods=['GET', 'POST'])
def newCar():
    if 'username' not in login_session:
        flash('Unauthorized Acces')
        return redirect(url_for('showCars'))
    if request.method == 'POST':
        newCar = Car(brand=request.form['brand'],
                     description=request.form['description'],
                     model=request.form['model'],
                     user_id=getUserID(login_session['email']))
        session.add(newCar)
        flash('New Car %s Successfully Created' % newCar.brand)
        session.commit()
        return redirect(url_for('showCars'))
    else:
        return render_template('newCar.html', login_session=login_session)


# Edit a car
@app.route('/car/<int:car_id>/edit/', methods=['GET', 'POST'])
def editCar(car_id):
    editedCar = session.query(Car).filter_by(id=car_id).one_or_none()
    if login_session['user_id']!=editedCar.user_id:
        flash('You must have user id %s to edit' % car_id)
        return redirect(url_for('showCars'))
    if 'username' not in login_session:
        flash('Unauthorized Acces')
        return redirect(url_for('showCars'))
    if request.method == 'POST':
        if request.form['brand']:
            editedCar.brand = request.form['brand']
        if request.form['model']:
            editedCar.model = request.form['model']
        if request.form['description']:
            editedCar.description = request.form['description']
        session.add(editedCar)
        session.commit
        flash('Car Successfully Edited %s' % editedCar.brand)
        return redirect(url_for('showCars'))
    else:
        return render_template('editCar.html', editedCar=editedCar,
                               car_id=car_id, login_session=login_session)


# Delete a car
@app.route('/car/<int:car_id>/delete/', methods=['GET', 'POST'])
def deleteCar(car_id):
    carToDelete = session.query(
        Car).filter_by(id=car_id).one_or_none()
    car_option = session.query(CarOption).filter_by(
        car_id=car_id).all()
    if login_session['user_id']!=carToDelete.user_id:
        flash('You must have user id %s to delete car' % car_id)
        return redirect(url_for('showCars'))
    if 'username' not in login_session:
        flash('Unauthorized Acces')
        return redirect(url_for('showCars'))
    if request.method == 'POST':
        session.delete(carToDelete)
        flash('%s Successfully Deleted' % carToDelete.brand)
        session.commit()
        return redirect(url_for('showCars'))
    else:
        return render_template('deleteCar.html', carToDelete=carToDelete,
                               car_id=car_id, car_option=car_option,
                               login_session=login_session)


# Show car option
@app.route('/car/<int:car_id>/')
@app.route('/car/<int:car_id>/options/')
def showOption(car_id):
    car = session.query(Car).filter_by(id=car_id).one_or_none()
    car_option = session.query(CarOption).filter_by(
        car_id=car_id).all()
    return render_template('options.html', car_option=car_option, car=car,
                           login_session=login_session)


# Create a new option
@app.route('/car/<int:car_id>/options/new/', methods=['GET', 'POST'])
def newOptionItem(car_id):
    car = session.query(Car).filter_by(id=car_id).one_or_none()
    if 'username' not in login_session:
        flash('Unauthorized Acces')
        return redirect(url_for('showCars'))
    if request.method == 'POST':
        newOption = CarOption(name=request.form['name'],
                              description=request.form['description'],
                              price=request.form['price'],
                              picture=request.form['picture'],
                              car_id=car_id,
                              user_id=car.user_id)
        session.add(newOption)
        session.commit()
        flash('New Option %s Successfully Created' % (newOption.name))
        return redirect(url_for('showOption', car_id=car_id))
    else:
        return render_template('newoptionitem.html', car_id=car_id,
                               login_session=login_session)


# Edit car option
@app.route('/car/<int:car_id>/options/<int:option_id>/edit',
           methods=['GET', 'POST'])
def editOption(car_id, option_id):
    editedOption = session.query(CarOption).filter_by(id=option_id).one_or_none()
    editedCar = session.query(Car).filter_by(id=car_id).one_or_none()
    if login_session['user_id']!=editedOption.user_id:
        flash('You must have user id %s to edit' % car_id)
        return redirect(url_for('showCars'))
    if 'username' not in login_session:
        flash('Unauthorized Acces')
        return redirect(url_for('showCars'))
    if request.method == 'POST':
        if request.form['name']:
            editedOption.name = request.form['name']
        if request.form['description']:
            editedOption.description = request.form['description']
        if request.form['price']:
            editedOption.price = request.form['price']
        if request.form['picture']:
            editedOption.course = request.form['picture']
        session.add(editedOption)
        session.commit()
        flash('Option Successfully Edited')
        return redirect(url_for('showOption', car_id=car_id))
    else:
        return render_template('editoptionitem.html', car_id=car_id,
                               option_id=option_id,
                               editedOption=editedOption, editedCar=editedCar,
                               login_session=login_session)


# Delete an option
@app.route('/car/<int:car_id>/options/<int:option_id>/delete',
           methods=['GET', 'POST'])
def deleteOption(car_id, option_id):
    car = session.query(Car).filter_by(id=car_id).one_or_none()
    optionToDelete = session.query(CarOption).filter_by(id=option_id).one_or_none()
    if login_session['user_id']!=optionToDelete.user_id:
        flash('You must have user id %s to delete' % car_id)
        return redirect(url_for('showCars'))
    if 'username' not in login_session:
        flash('Unauthorized Acces')
        return redirect(url_for('showCars'))
    if request.method == 'POST':
        session.delete(optionToDelete)
        session.commit()
        flash('Option Successfully Deleted')
        return redirect(url_for('showOption', car_id=car_id))
    else:
        return render_template('deleteoptionitem.html',
                               optionToDelete=optionToDelete, car=car,
                               login_session=login_session)


if __name__ == '__main__':
    app.secret_key = 'ABCDE12345'
    app.debug = True
    app.run(host='0.0.0.0', port=5000)
