# main.py
import os
from flask import Blueprint, render_template,request,flash,redirect,url_for
from flask_login import login_required, current_user
from .models import Book,User
from . import db
cwd = os.getcwd()
print(cwd)

UPLOAD_FOLDER = 'project/static/uploads/'

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return render_template('index.html')

@main.route('/profile')
@login_required
def profile():

    return render_template('profile.html', name=current_user.name)

@main.route('/upload', methods=['POST','GET'])
@login_required
def upload():
    print('salam')

    if request.method == 'POST':

        filename = request.files['filename']
        filepath = os.path.join(UPLOAD_FOLDER,filename.filename)
        filename.save(filepath)

        imagename = request.files['imagename']
        imagepath = os.path.join(UPLOAD_FOLDER, imagename.filename)
        imagename.save(imagepath)
        print('Files saved sucessfully in \n',imagepath)
        print('Files saved sucessfully in \n', filepath)
        name = request.form.get('name')
        book = Book.query.filter_by(
            name=name).first()  # if this returns a user, then the email already exists in database

        if book:  # if a user is found, we want to redirect back to signup page so user can try again
            flash('Email address already exists')
            return redirect(url_for('main.upload'))

        # create new user with the form data. Hash the password so plaintext version isn't saved.
        new_book = Book(filename=filename.filename,
                        name=name,imagename=imagename.filename,
                        username=current_user.name)

        # add the new user to the database
        db.session.add(new_book)
        db.session.commit()

        return redirect(url_for('main.books'))
    # return render_template('index.html',upload=False)

    return render_template('upload.html',upload=False)


@main.route('/books')
@login_required
def books():
    books = Book.query.all()

    return render_template('books.html',books=books)
