from flask import Blueprint, render_template, request, flash, redirect, url_for
from flask_login import login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from .models import User, Art
from . import db

from . import dispatch
from app.lib import clean_file as cf
from app.lib import tools

dashboards = Blueprint('dashboards', __name__)

# Main Pages
@dashboards.route('/', methods=['GET', 'POST'])
def market():
    return render_template('market.html', user=current_user)
	
@dashboards.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
    # fetch post request
    if request.method == "POST":
        cpasswd = request.form.get('current_password')
        passwd = request.form.get('password')
        passwd_con = request.form.get('password_confirm')

        # password check before update
        if passwd and passwd_con and cpasswd:
            if passwd == passwd_con and check_password_hash(current_user.password, cpasswd):
                npasswd_dbcall = User.query.filter_by(id=current_user.id).first()
                npasswd_dbcall.password = generate_password_hash(passwd_con, method='sha256')
                db.session.commit()
                flash('Updated password!', category='success')
            else:
                flash('Password update failed!', category='error')

    my_art = Art.query.filter_by(owner=current_user.id).all()
    my_creation = Art.query.filter_by(creator=current_user.id).all()

    return render_template('profile.html', user = current_user, my_art = my_art, my_creation = my_creation)

@dashboards.route('/create_art', methods=['GET', 'POST'])
@login_required
def create():
    # check POST req
    if request.method == "POST":
        new_art = request.files.get('art_img')
        art_name = request.form.get('art_name')
        art_desc = request.form.get('description')
        min_price = request.form.get('minimum_price')
        buyout_price = request.form.get('buyout_price')
        close_date = request.form.get('closing_date')

        if tools.check_fields([new_art, art_name, min_price, buyout_price, close_date]):
            if new_art and new_art.filename != '' and cf.allowed_file(new_art.filename):
                designated_fn = cf.sanitize(new_art.filename)
                new_art.save(f'{cf.UPLOAD_FOLDER}/{designated_fn}')
                dispatch.mint(designated_fn, art_name, art_desc, min_price, buyout_price, close_date)

    return render_template('create_art.html', user=current_user)
	
# Pop Ups
@dashboards.route('/modal_home')
@login_required
def modal_home():
    return render_template('detail_art_for_home.html', user=current_user)

@dashboards.route('/modal_profile')
@login_required
def modal_profile():
    return render_template('detail_art_for_profile.html', user=current_user)
