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

from config import CONFIG 
from create_db import User, Card

import nextcloud_client


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

engine = create_engine(CONFIG['DB_CONNECTION'])
dbsessionmaker = sessionmaker(bind=engine)
dbsession = dbsessionmaker()


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("menu/upload.html", username=username)


@bp.route('/uploader', methods = ('GET', 'POST'))
def upload_file():
    user_id = session["user_id"]
    username = session["username"]
    message = ""
    if request.method == 'POST':
        #flask gets the file
        upload = request.files["file"]
        filename = secure_filename(upload.filename)

        script_path = os.path.dirname(os.path.abspath(__file__))
        temp_path = os.path.join(script_path, "temp")
        

        #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()
            nc.put_file("/GIA CLOUD/" + filename, path)
            os.remove(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)
        dbsession.add(card)
        dbsession.commit()
        
    return render_template("menu/upload.html", message=message, user_id=user_id, username=username)
