from flask import Blueprint, render_template, redirect, url_for, request, flash
from flask.ext.login import login_required, login_user, logout_user
from werkzeug import check_password_hash, generate_password_hash

from app import db, login_manager, pubnub, app, _callback
from .models import User
from .forms import LoginForm, SignupForm

mod_auth = Blueprint('auth', __name__)

@mod_auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)
    error = None
    print(request.method)
    if request.method == 'POST':
        user = db.users.find_one({'username': request.form['username']})
        if not user:
            error = 'User does not exist'
        elif not check_password_hash(user['password'], request.form['password']):
            error = 'Invalid credentials. Please try again.'
        else:
            user_obj = User(user['username'])
            login_user(user_obj)
            return redirect(url_for('devices.list_devices'))
    return render_template('auth/login.html',
                           title='Log In to Hydrosmart',
                           form=form,
                           error=error)

@mod_auth.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignupForm(request.form)
    error = None
    if request.method == 'POST':
        existing_user = db.users.find_one({'username' :
                                           request.form['username']})
        if existing_user:
            error = 'Username already exists'
        else:
            new_user = {'username' : request.form['username'],
                        'email' : request.form['email'],
                        'zip' : request.form['zip'],
                        'password' : generate_password_hash(request.form['password'])}
            db.users.insert_one(new_user)
            user = db.users.find_one({'username': request.form['username']})
            pubnub.channel_group_add_channel(channel_group=app.config['PUBNUB_CHANNEL_GRP'], channel=user['username'])
            pubnub.grant(channel=user['username'], auth_key=app.config['PUBNUB_AUTH_KEY'], read=True, write=True, manage=True, ttl=0)
            return redirect(url_for('dashboard.dashboard'))
    return render_template('auth/signup.html', form=form,
                           title='Sign Up for Hydrosmart', error=error)

# @mod_auth.route('/googlelogin', methods=['GET', 'POST'])

@mod_auth.route("/logout")
@login_required
def logout():
    logout_user()
    flash("Logged out.")
    return redirect('/login')

@login_manager.unauthorized_handler
def unauthorized_callback():
  return redirect('/login')

@login_manager.user_loader
def load_user(username):
  u = db.users.find_one({'username': username})
  if not u:
      return None
  return User(u['username'])

def callback(message, channel):
  db.data.insert_one(message)

def error(message):
  db.data.insert_one(message)

[((9, 11, 9, 38), 'flask.Blueprint', 'Blueprint', ({(9, 21, 9, 27): '"""auth"""', (9, 29, 9, 37): '__name__'}, {}), "('auth', __name__)", False, 'from flask import Blueprint, render_template, redirect, url_for, request, flash\n'), ((26, 11, 29, 39), 'flask.render_template', 'render_template', (), '', False, 'from flask import Blueprint, render_template, redirect, url_for, request, flash\n'), ((50, 11, 51, 71), 'flask.render_template', 'render_template', (), '', False, 'from flask import Blueprint, render_template, redirect, url_for, request, flash\n'), ((58, 4, 58, 17), 'flask.ext.login.logout_user', 'logout_user', ({}, {}), '()', False, 'from flask.ext.login import login_required, login_user, logout_user\n'), ((59, 4, 59, 24), 'flask.flash', 'flash', ({(59, 10, 59, 23): '"""Logged out."""'}, {}), "('Logged out.')", False, 'from flask import Blueprint, render_template, redirect, url_for, request, flash\n'), ((60, 11, 60, 29), 'flask.redirect', 'redirect', ({(60, 20, 60, 28): '"""/login"""'}, {}), "('/login')", False, 'from flask import Blueprint, render_template, redirect, url_for, request, flash\n'), ((64, 9, 64, 27), 'flask.redirect', 'redirect', ({(64, 18, 64, 26): '"""/login"""'}, {}), "('/login')", False, 'from flask import Blueprint, render_template, redirect, url_for, request, flash\n'), ((68, 6, 68, 47), 'app.db.users.find_one', 'db.users.find_one', ({(68, 24, 68, 46): "{'username': username}"}, {}), "({'username': username})", False, 'from app import db, login_manager, pubnub, app, _callback\n'), ((74, 2, 74, 29), 'app.db.data.insert_one', 'db.data.insert_one', ({(74, 21, 74, 28): 'message'}, {}), '(message)', False, 'from app import db, login_manager, pubnub, app, _callback\n'), ((77, 2, 77, 29), 'app.db.data.insert_one', 'db.data.insert_one', ({(77, 21, 77, 28): 'message'}, {}), '(message)', False, 'from app import db, login_manager, pubnub, app, _callback\n'), ((17, 15, 17, 72), 'app.db.users.find_one', 'db.users.find_one', ({(17, 33, 17, 71): "{'username': request.form['username']}"}, {}), "({'username': request.form['username']})", False, 'from app import db, login_manager, pubnub, app, _callback\n'), ((36, 24, 37, 69), 'app.db.users.find_one', 'db.users.find_one', ({(36, 42, 37, 68): "{'username': request.form['username']}"}, {}), "({'username': request.form['username']})", False, 'from app import db, login_manager, pubnub, app, _callback\n'), ((45, 12, 45, 41), 'app.db.users.insert_one', 'db.users.insert_one', ({(45, 32, 45, 40): 'new_user'}, {}), '(new_user)', False, 'from app import db, login_manager, pubnub, app, _callback\n'), ((46, 19, 46, 76), 'app.db.users.find_one', 'db.users.find_one', ({(46, 37, 46, 75): "{'username': request.form['username']}"}, {}), "({'username': request.form['username']})", False, 'from app import db, login_manager, pubnub, app, _callback\n'), ((47, 12, 47, 118), 'app.pubnub.channel_group_add_channel', 'pubnub.channel_group_add_channel', (), '', False, 'from app import db, login_manager, pubnub, app, _callback\n'), ((48, 12, 48, 133), 'app.pubnub.grant', 'pubnub.grant', (), '', False, 'from app import db, login_manager, pubnub, app, _callback\n'), ((20, 17, 20, 80), 'werkzeug.check_password_hash', 'check_password_hash', ({(20, 37, 20, 53): "user['password']", (20, 55, 20, 79): "request.form['password']"}, {}), "(user['password'], request.form['password'])", False, 'from werkzeug import check_password_hash, generate_password_hash\n'), ((24, 12, 24, 32), 'flask.ext.login.login_user', 'login_user', ({(24, 23, 24, 31): 'user_obj'}, {}), '(user_obj)', False, 'from flask.ext.login import login_required, login_user, logout_user\n'), ((44, 37, 44, 85), 'werkzeug.generate_password_hash', 'generate_password_hash', ({(44, 60, 44, 84): "request.form['password']"}, {}), "(request.form['password'])", False, 'from werkzeug import check_password_hash, generate_password_hash\n'), ((49, 28, 49, 58), 'flask.url_for', 'url_for', ({(49, 36, 49, 57): '"""dashboard.dashboard"""'}, {}), "('dashboard.dashboard')", False, 'from flask import Blueprint, render_template, redirect, url_for, request, flash\n'), ((25, 28, 25, 59), 'flask.url_for', 'url_for', ({(25, 36, 25, 58): '"""devices.list_devices"""'}, {}), "('devices.list_devices')", False, 'from flask import Blueprint, render_template, redirect, url_for, request, flash\n')]