from flask import Blueprint, render_template, redirect, url_for, request, flash,session
from flask_login import login_user, logout_user, login_required, current_user
from functools import wraps
from webapp.models.user import *

from webapp import db

auth = Blueprint('auth', __name__)


def admin_required(f):
	@wraps(f)
	def wrap(*args, **kwargs):
		if "_user_id" in session :
			query=User.query.filter(User.id==int(session["_user_id"]),
				User.account_type=="admin", User.active==True).first()
			if query:
				return f(*args, **kwargs)
			else:
				return redirect(url_for("auth.logout"))
		else:
			return redirect(url_for("auth.logout"))
			# return redirect(url_for('login_page'))

	return wrap



def datecurrent():
	return datetime.now()

@auth.route('/login')
def login():
	title='USER LOGIN'
	url="/login"
	return render_template('login.html', title=title, url=url)




@auth.route('/login', methods=['POST'])
def login_post():
	data=request.form.to_dict(flat=True)
	name=request.form.get('username')
	psd=request.form.get('password')
	remember = True if request.form.get('remember') else False
	if name=="test":
		user=User.query.filter_by(username=name,active=True).first()
		if user:
			if check_password_hash(user.password, psd):
				session["type"]="user"
				login_user(user)
				return redirect(url_for("auth.signup_admin"))
			else:
				return redirect(url_for("auth.login", title="USER LOGIN", url="/login"))
		else:
			test=User(username="test",account_type="admin", password=generate_password_hash("test", method='pbkdf2:sha256'))
			db.session.add(test)
			db.session.commit()
			login_user(test)
			return redirect(url_for("auth.signup_admin"))
	else:
		user=User.query.filter(User.username==name,User.active==True).first()
		if user and check_password_hash(user.password, psd):
			session["type"]=user.account_type
			session["username"]=user.username
			login_user(user)
			return redirect(url_for("frontoffice.index"))
		else:
			return redirect(url_for('auth.login'))
		


@auth.route("/signup/admin", methods=["GET"])
@admin_required
def signup_admin():
	title='CREATE ADMIN LOGIN'
	url="/signup/admin"
	return render_template('login_admin.html', title=title, url=url)


@auth.route("/signup/admin", methods=["POST"])
@admin_required
@login_required
def signup_admin_post():
	name=request.form.get('username')
	psd=request.form.get('password')
	user=User.query.filter_by(username=name).first()
	if user:
		return redirect(url_for('auth.signup_admin'))
	new_user=User(username=name,account_type="admin",active=True,password=generate_password_hash(psd, method='pbkdf2:sha256'))
	db.session.add(new_user)
	User.query.filter(User.username=="test").update({
		User.active: False
		})
	db.session.commit()
	logout_user()
	return redirect(url_for('auth.login'))


# @auth.route('/signup')
# def signup():
# 	return render_template('signin.html')
	

@auth.route('/logout')
@login_required
def logout():
	current=current_user
	if current.__tablename__=="_user":
		logout_user()
		return redirect(url_for('auth.login'))
	else:
		logout_user()
		return redirect(url_for("booking.booking_homepage"))
	
	
	
@auth.route('/signup', methods=['POST'])
def signup_post():
	name=request.form.get('name')
	psd=request.form.get('psd')
	user=User.query.filter_by(username=name).first()	
	if user:
		flash('User address already exists')
		return redirect(url_for('auth.signup'))
	new_user=User(username=name, password=generate_password_hash(psd, method='pbkdf2:sha256'))
	db.session.add(new_user)
	User.query.filter(User.username=="test").update({
		User.active: False
		})
	db.session.commit()
	return redirect(url_for('auth.login'))



@auth.route('/client/login', methods=['POST'])
def client_login_post():
	email=request.form.get('email')
	password=request.form.get('password')
	client=Client.query.filter(Client.email==email.strip(),Client.active==True).first()
	if client and check_password_hash(client.password, password):
		session["type"]="client"
		login_user(client)
		return redirect(url_for("booking.client_dashboard"))
	else:
		flash('PASSWORD OR EMAIL ERROR!', 'danger')
		return redirect(url_for("booking.booking_homepage"))
		