import tempfile
import os
from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.utils import secure_filename 
from auth import login_required

from config import CONFIG 
from create_db import User, Card, get_session

import nextcloud_client
import magic

bp = Blueprint('upload', __name__, url_prefix='/upload')


nc = nextcloud_client.Client('https://obzorje.kompot.si')
#print("Loggin in", CONFIG['NC_USER'], CONFIG['NC_PASSWORD'])
nc.login(CONFIG['NC_USER'],CONFIG['NC_PASSWORD'])


@bp.route("/", methods=["GET", "POST"])
def index():
    username = session["username"]
    return render_template("upload.html", username=username)


@bp.route('/uploader', methods = ('GET', 'POST'))
def upload_file():
    dbsession = get_session()

    user_id = session["user_id"]
    username = session["username"]
    
    if request.method == 'POST':
        #@TODO ta forloop bi lahko flashal postopoma
        for upload in request.files.getlist("file"):
            filename = secure_filename(upload.filename)
            # Is there really a file?
            if not filename:
                flash('There is no file. Try again?')
                return render_template("upload.html", username=username)

            #prevent duplicate filenames
            print(filename)
            if dbsession.query(Card).filter(Card.title == filename).first() != None:
                flash("Filename already in database, please rename if you want to upload: " + filename, 'error')
                continue

            script_path = os.path.dirname(os.path.abspath(__file__))    #where are we
            temp_path = os.path.join(script_path, "temp")               #where is the temp file
            
            # a lot of stuff can wrong here and nobody may know
            with tempfile.NamedTemporaryFile(dir=temp_path, delete=False) as fp:
                fp.write(upload.stream.read())
                path = fp.name
                fp.close()
                if magic.from_file(path, mime=True) == "application/pdf":
                    nc.put_file("/GIA CLOUD/" + filename, path)
                    #get public link
                    public_link = nc.share_file_with_link("/GIA CLOUD/" + filename).get_link()+"/download/"+filename
                    
                    #add card
                    card = Card(title=filename, interest_rate=-1.0, owner_id=user_id, item_location=public_link, last_review=None, share_id=0)
                    flash(f"{filename} uploaded successfully")
                    dbsession.add(card)
                    dbsession.commit()
                    dbsession.close()
                else:
                    flash("Please insert a PDF file, support for other formats comming soon...")
                    #return render_template("upload.html", user_id=user_id, username=username)

                os.remove(path)

        
    return render_template("upload.html", user_id=user_id, username=username)
