# app/auth/views.py
import os
from flask import flash, redirect, render_template, url_for, request
from flask_login import login_required, login_user, logout_user, current_user
from . import auth
from .forms import (LoginForm, RegistrationForm,
                    RequestResetForm, ResetPasswordForm)
from .. import db, mail
from ..models import User
from flask_mail import Message
from werkzeug.security import generate_password_hash


@auth.route('/register/', methods=['GET', 'POST'])
def register():
    """
    Handle requests to the /register route
    Add an user to the database through the registration form
    """
    logout_user()
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    email=form.email.data,
                    username=form.username.data,
                    password=form.password.data,
                    is_freelancer=form.freelancer.data,
                    is_employer=form.employer.data)
        # add user to the database
        db.session.add(user)
        db.session.commit()
        flash(f'You have successfully registered! You may now login', 'success')

        # redirect to the login page

        return redirect(url_for('auth.login'))
    # load registration form
    return render_template('auth/register.html', form=form, title='Register')


@auth.route('/login/', methods=['GET', 'POST'])
def login():
    """
    Handle requests to the /login route
    Log an employee in through the login form
    """
    if current_user.is_authenticated:
        if current_user.is_freelancer == True and current_user.is_employer == False:
            # redirect to the freelancer dashboard page after login
            return redirect(url_for('freelancer.dashboard'))
        elif current_user.is_employer == True and current_user.is_freelancer == False:
            # redirect to the employer dashboard page after login
            return redirect(url_for('employer.dashboard'))
        elif current_user.is_employer and current_user.is_freelancer:
            # redirect to the employer dashboard page after login
            return redirect(url_for('employer.dashboard'))
        else:
            # redirect to the admin dashboard
            return redirect(url_for('admin.admin_dashboard'))

    form = LoginForm()
    if form.validate_on_submit():
        # check whether user exists in the database
        # the password entered matches the password in the database

        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, remember=form.remember.data)
            #flash(f'Logged In', 'success')
            if user.is_freelancer == True and user.is_employer == False:
                # redirect to the freelancer dashboard page after login
                return redirect(url_for('freelancer.dashboard'))
            elif user.is_employer == True and user.is_freelancer == False:
                # redirect to the employer dashboard page after login
                return redirect(url_for('employer.dashboard'))
            elif user.is_employer and user.is_freelancer:
                # redirect to the employer dashboard page after login
                return redirect(url_for('employer.dashboard'))
            else:
                # redirect to the admin dashboard
                return redirect(url_for('admin.admin_dashboard'))
        flash(f'Invalid Credentials', 'danger')
    # load login template
    return render_template('auth/login.html', form=form, title='Login')


@auth.route('/logout/', methods=['GET', 'POST'])
@login_required
def logout():
    """
    Handle requests to the /logout route
    Log an employee out through the logout link
    """
    logout_user()
    flash(f'You have been logged out', 'success')
    # redirect to the login page
    return redirect(url_for('auth.login'))


def send_reset_email(user):
    
    try:
        token = user.get_reset_token()
        msg = Message('Password Reset Request',
                      sender='activecodar@gmail.com',
                      recipients=[user.email])
        msg.body = f''' To reset your password visit the following link
        {url_for('auth.reset_password', token=token, _external=True)}

        If you did not make this request ignore this email
        '''
        mail.send(msg)
        
    except Exception as e:
        print(e)


@auth.route('/reset-password', methods=['GET', 'POST'])
def request_reset():
    if current_user.is_authenticated:
        next_page = request.args.get('next')
        if current_user.is_freelancer == True and current_user.is_employer == False:
            # redirect to the freelancer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('freelancer.dashboard'))
        elif current_user.is_employer == True and current_user.is_freelancer == False:
            # redirect to the employer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('employer.dashboard'))
        elif current_user.is_employer and current_user.is_freelancer:
            # redirect to the employer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('employer.dashboard'))
        else:
            # redirect to the admin dashboard
            return redirect(next_page) if next_page else redirect(url_for('admin.admin_dashboard'))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash(f'Email has been sent with password reset instructions', 'info')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_request.html', form=form, title='Request Reset Password')


@auth.route('/reset-password/<token>', methods=['GET', 'POST'])
def reset_password(token):
    if current_user.is_authenticated:
        next_page = request.args.get('next')
        if current_user.is_freelancer == True and current_user.is_employer == False:
            # redirect to the freelancer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('freelancer.dashboard'))
        elif current_user.is_employer == True and current_user.is_freelancer == False:
            # redirect to the employer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('employer.dashboard'))
        elif current_user.is_employer and current_user.is_freelancer:
            # redirect to the employer dashboard page after login
            return redirect(next_page) if next_page else redirect(url_for('employer.dashboard'))
        else:
            # redirect to the admin dashboard
            return redirect(next_page) if next_page else redirect(url_for('admin.admin_dashboard'))

    user = User.verify_reset_token(token)

    if user is None:
        flash(f'Invalid token or expired token', 'warning')
        return redirect(url_for('auth.request_reset'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        # add user to the database
        hashed_password = generate_password_hash(form.password.data)
        user.password_hash = hashed_password
        db.session.commit()
        flash(
            f'Your password has been reset successfully! You may now login', 'success')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_password.html', form=form, title='Reset Password')

[((20, 4, 20, 17), 'flask_login.logout_user', 'logout_user', ({}, {}), '()', False, 'from flask_login import login_required, login_user, logout_user, current_user\n'), ((39, 11, 39, 77), 'flask.render_template', 'render_template', (), '', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((85, 11, 85, 71), 'flask.render_template', 'render_template', (), '', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((95, 4, 95, 17), 'flask_login.logout_user', 'logout_user', ({}, {}), '()', False, 'from flask_login import login_required, login_user, logout_user, current_user\n'), ((96, 4, 96, 49), 'flask.flash', 'flash', ({(96, 10, 96, 37): 'f"""You have been logged out"""', (96, 39, 96, 48): '"""success"""'}, {}), "(f'You have been logged out', 'success')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((141, 11, 141, 96), 'flask.render_template', 'render_template', (), '', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((175, 11, 175, 89), 'flask.render_template', 'render_template', (), '', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((33, 8, 33, 80), 'flask.flash', 'flash', ({(33, 14, 33, 68): 'f"""You have successfully registered! You may now login"""', (33, 70, 33, 79): '"""success"""'}, {}), "(f'You have successfully registered! You may now login', 'success')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((83, 8, 83, 47), 'flask.flash', 'flash', ({(83, 14, 83, 36): 'f"""Invalid Credentials"""', (83, 38, 83, 46): '"""danger"""'}, {}), "(f'Invalid Credentials', 'danger')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((98, 20, 98, 41), 'flask.url_for', 'url_for', ({(98, 28, 98, 40): '"""auth.login"""'}, {}), "('auth.login')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((105, 14, 107, 46), 'flask_mail.Message', 'Message', (), '', False, 'from flask_mail import Message\n'), ((122, 20, 122, 44), 'flask.request.args.get', 'request.args.get', ({(122, 37, 122, 43): '"""next"""'}, {}), "('next')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((139, 8, 139, 78), 'flask.flash', 'flash', ({(139, 14, 139, 69): 'f"""Email has been sent with password reset instructions"""', (139, 71, 139, 77): '"""info"""'}, {}), "(f'Email has been sent with password reset instructions', 'info')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((147, 20, 147, 44), 'flask.request.args.get', 'request.args.get', ({(147, 37, 147, 43): '"""next"""'}, {}), "('next')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((164, 8, 164, 59), 'flask.flash', 'flash', ({(164, 14, 164, 47): 'f"""Invalid token or expired token"""', (164, 49, 164, 58): '"""warning"""'}, {}), "(f'Invalid token or expired token', 'warning')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((169, 26, 169, 68), 'werkzeug.security.generate_password_hash', 'generate_password_hash', ({(169, 49, 169, 67): 'form.password.data'}, {}), '(form.password.data)', False, 'from werkzeug.security import generate_password_hash\n'), ((172, 8, 173, 87), 'flask.flash', 'flash', ({(173, 12, 173, 75): 'f"""Your password has been reset successfully! You may now login"""', (173, 77, 173, 86): '"""success"""'}, {}), "(f'Your password has been reset successfully! You may now login',\n    'success')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((37, 24, 37, 45), 'flask.url_for', 'url_for', ({(37, 32, 37, 44): '"""auth.login"""'}, {}), "('auth.login')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((69, 12, 69, 57), 'flask_login.login_user', 'login_user', (), '', False, 'from flask_login import login_required, login_user, logout_user, current_user\n'), ((140, 24, 140, 45), 'flask.url_for', 'url_for', ({(140, 32, 140, 44): '"""auth.login"""'}, {}), "('auth.login')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((165, 24, 165, 53), 'flask.url_for', 'url_for', ({(165, 32, 165, 52): '"""auth.request_reset"""'}, {}), "('auth.request_reset')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((174, 24, 174, 45), 'flask.url_for', 'url_for', ({(174, 32, 174, 44): '"""auth.login"""'}, {}), "('auth.login')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((51, 28, 51, 59), 'flask.url_for', 'url_for', ({(51, 36, 51, 58): '"""freelancer.dashboard"""'}, {}), "('freelancer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((109, 29, 109, 88), 'flask.url_for', 'url_for', (), '', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((125, 19, 125, 38), 'flask.redirect', 'redirect', ({(125, 28, 125, 37): 'next_page'}, {}), '(next_page)', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((150, 19, 150, 38), 'flask.redirect', 'redirect', ({(150, 28, 150, 37): 'next_page'}, {}), '(next_page)', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((54, 28, 54, 57), 'flask.url_for', 'url_for', ({(54, 36, 54, 56): '"""employer.dashboard"""'}, {}), "('employer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((73, 32, 73, 63), 'flask.url_for', 'url_for', ({(73, 40, 73, 62): '"""freelancer.dashboard"""'}, {}), "('freelancer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((125, 66, 125, 97), 'flask.url_for', 'url_for', ({(125, 74, 125, 96): '"""freelancer.dashboard"""'}, {}), "('freelancer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((128, 19, 128, 38), 'flask.redirect', 'redirect', ({(128, 28, 128, 37): 'next_page'}, {}), '(next_page)', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((150, 66, 150, 97), 'flask.url_for', 'url_for', ({(150, 74, 150, 96): '"""freelancer.dashboard"""'}, {}), "('freelancer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((153, 19, 153, 38), 'flask.redirect', 'redirect', ({(153, 28, 153, 37): 'next_page'}, {}), '(next_page)', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((57, 28, 57, 57), 'flask.url_for', 'url_for', ({(57, 36, 57, 56): '"""employer.dashboard"""'}, {}), "('employer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((60, 28, 60, 60), 'flask.url_for', 'url_for', ({(60, 36, 60, 59): '"""admin.admin_dashboard"""'}, {}), "('admin.admin_dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((76, 32, 76, 61), 'flask.url_for', 'url_for', ({(76, 40, 76, 60): '"""employer.dashboard"""'}, {}), "('employer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((128, 66, 128, 95), 'flask.url_for', 'url_for', ({(128, 74, 128, 94): '"""employer.dashboard"""'}, {}), "('employer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((131, 19, 131, 38), 'flask.redirect', 'redirect', ({(131, 28, 131, 37): 'next_page'}, {}), '(next_page)', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((134, 19, 134, 38), 'flask.redirect', 'redirect', ({(134, 28, 134, 37): 'next_page'}, {}), '(next_page)', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((153, 66, 153, 95), 'flask.url_for', 'url_for', ({(153, 74, 153, 94): '"""employer.dashboard"""'}, {}), "('employer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((156, 19, 156, 38), 'flask.redirect', 'redirect', ({(156, 28, 156, 37): 'next_page'}, {}), '(next_page)', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((159, 19, 159, 38), 'flask.redirect', 'redirect', ({(159, 28, 159, 37): 'next_page'}, {}), '(next_page)', False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((79, 32, 79, 61), 'flask.url_for', 'url_for', ({(79, 40, 79, 60): '"""employer.dashboard"""'}, {}), "('employer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((82, 32, 82, 64), 'flask.url_for', 'url_for', ({(82, 40, 82, 63): '"""admin.admin_dashboard"""'}, {}), "('admin.admin_dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((131, 66, 131, 95), 'flask.url_for', 'url_for', ({(131, 74, 131, 94): '"""employer.dashboard"""'}, {}), "('employer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((134, 66, 134, 98), 'flask.url_for', 'url_for', ({(134, 74, 134, 97): '"""admin.admin_dashboard"""'}, {}), "('admin.admin_dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((156, 66, 156, 95), 'flask.url_for', 'url_for', ({(156, 74, 156, 94): '"""employer.dashboard"""'}, {}), "('employer.dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n'), ((159, 66, 159, 98), 'flask.url_for', 'url_for', ({(159, 74, 159, 97): '"""admin.admin_dashboard"""'}, {}), "('admin.admin_dashboard')", False, 'from flask import flash, redirect, render_template, url_for, request\n')]