import os
from flask import Flask, send_from_directory
from flask import (
    Blueprint, session, flash, redirect, render_template, request, url_for
)

from werkzeug.utils import secure_filename

from Uploadr.db import get_files, get_file_name, file_insert, file_remove



app = Flask(__name__)
app.config.from_mapping(
    UPLOAD_FOLDER='/users/figo/public_html/wsgi/Uploadr/uploads',
    MAX_CONTENT_LENGTH = 100 * 1000,
)


bp = Blueprint('files', __name__)

@bp.route('/')
def index():
    if session and session['user_id']:      
        files = get_files(session['user_id'])
        return render_template('files/index.html',files=files)   
    else:                
        return redirect(url_for("auth.login"))
       
@bp.route('/delete/<int:id>')
def delete(id):
    if session and session['user_id']:
        try:
            name = get_file_name(id)
            os.remove(os.path.join(app.config['UPLOAD_FOLDER'], str(session['user_id']) + name))
            file_remove(id)   
        except: 
            flash(f"No file exists with id {id}")

        
        return redirect(url_for('index')) 
    
    return redirect(url_for('auth.login'))

@bp.route('/download/<int:id>')
def download(id):
    if session and session['user_id']:    
        try:
            name = get_file_name(id)
            return send_from_directory(app.config["UPLOAD_FOLDER"], str(session['user_id']) + name )
        except: 
            flash(f"No file exists with id {id}")

        return redirect(url_for('index'))  
    
    return redirect(url_for('auth.login'))      

@bp.route('/upload', methods=('GET', 'POST'))
def upload():
    if session and session['user_id']:  
        if request.method == 'POST':
            # check if the post request has the file part
            if 'file' not in request.files:
                flash('No file part')
                return redirect(request.url)
            file = request.files['file']
            # If the user does not select a file, the browser submits an
            # empty file without a filename.
            if file.filename == '':
                flash('No selected file')
                return redirect(request.url)
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename) 
                error = file_insert(filename)
                if error is not None:
                    flash(error)
                    return redirect(request.url) 
                else:
                    file.save(os.path.join(app.config['UPLOAD_FOLDER'], str(session['user_id']) + filename ))
                    return redirect(url_for('index'))                  
            else:
                return redirect(url_for('index'))

        return render_template('files/upload.html')
    
    return redirect(url_for('auth.login'))      

def allowed_file(filename):
    ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS