from flask import render_template, url_for, flash, redirect, request, Blueprint
from flask_login import login_user, current_user, logout_user, login_required
from puppycompanyblog import db
from puppycompanyblog.models import User, BlogPost
from puppycompanyblog.users.forms import RegistrationForm, LoginForm, UpdateUserForm
from puppycompanyblog.users.picture_handler import add_profile_pic


users = Blueprint('users', __name__)



#register
@users.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()

    if form.validate_on_submit():

        user = User(email = form.email.data,
                    username = form.username.data,
                    password=form.password.data)

        #dodawanie do bazy
        db.session.add(user)
        db.session.commit()

        flash('Thanks for registration!')
        return redirect(url_for('users.login'))

    return render_template('register.html', form=form)


#login
@users.route('/login', methods=['GET', 'POST'])
def login():
    
    form = LoginForm()

    if form.validate_on_submit():

        user = User.query.filter_by(email=form.email.data).first()

        if user.check_password(form.password.data) and user is not None:

            login_user(user)
            flash('Log in Success!')

            next = request.args.get('next') # what user is trying to acces

            if next == None or not next[0]=='/':
                next = url_for('core.index')

            return redirect(next)

    return render_template('login.html', form=form)



#log out
@users.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('core.index'))


#account( Update user form)

@users.route('/account', methods=['GET', 'POST'])
@login_required # Must be logged in to see this view, daje tez funkcjonalnosc current_user
def account():

    form = UpdateUserForm()

    if form.validate_on_submit():

        if form.picture.data: #If someone submitted to picture file from formsss
            username = current_user.username
            pic = add_profile_pic(form.picture.data, username)
            current_user.profile_image = pic

        current_user.username = form.username.data
        current_user.email = form.email.data
        db.session.commit() # Send data to dadabase
        
        flash('User Account Updated!')
        return redirect(url_for('users.account'))

    elif request.method == 'GET':
        form.username.data = current_user.username
        form.email.data = current_user.email

    #Renderowanie template for account page (default)
    profile_image = url_for('static', filename='profile_pics/' + current_user.profile_image)
    
                                            #przekazanie obrazka (linka do obrazka)
    return render_template('account.html', profile_image=profile_image, form=form)



# user's list of blog posts

@users.route('/<username>') #username moze byc rozne
def user_posts(username):
    page = request.args.get('page', 1, type=int) # pozwala na cycle through posty uzytkownika (rozdzielenie na karty w bootstrapie w templacie trzeba bedzie jeszcze pozmieniac)
    user = User.query.filter_by(username=username).first_or_404() #jak nie ma usera to wyswietli sie blad 404
    blog_posts = BlogPost.query.filter_by(author = user).order_by(BlogPost.date.desc()).paginate(page=page, per_page=5) #Zwraca obiekt paginate SQLalchemy ktore ma pole items
    render_template('user_blog_posts.html', blog_posts=blog_posts, user=user)
