from flask import (
    Blueprint, render_template, request, session, flash
)
from create_db import Card, get_session, get_engine
from link_handler import check_link
from werkzeug.utils import secure_filename
import tempfile
import os


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


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


@bp.route('/import', methods = ('GET', 'POST'))
def import_link():
    username = session['username']
    user_id = session['user_id']
    if request.method == 'POST':
        import_type = request.form.get("import_txt")
        print("###########################", import_type)
        if import_type == "import_txt":
            return render_template("import_txt.html", user_id=user_id, username=username)
        else:
            link = request.form.get("import_link", False)
            commit_link(link=link, user_id=user_id)

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


def commit_link(link, user_id):

    Session = get_session()
    with Session() as dbsession:
        existing_link = dbsession.query(Card).filter_by(owner_id=user_id, item_location=link).first()
        if existing_link:
            print(f"{link} has already been imported.")
            flash(f"{link} has already been imported.","error")
            return -1
        
        link_check = check_link(link)
        if link_check != 1:
            print(link, 'is not ok')
            flash(f"{link}, 'is not ok', {link_check}", "rror")
            return -1
        else:
            print(link, 'is ok')
        #add card
        #TODO ni razlike med title in vsebino urlja ??
            card = Card(title=link,
                        interest_rate=-1.0, 
                        owner_id=user_id, 
                        item_location=link, 
                        last_review=None,
                        card_type="URL", 
                        share_id=0)
            dbsession.add(card)
            dbsession.commit()
        
        flash(f"{card.title} imported successfully")
        dbsession.close()
    
    get_engine().disolve()
    return 1

@bp.route('/import_txt', methods = ('GET', 'POST'))
def import_link_from_txt():
    user_id = session["user_id"]
    username = session["username"]
    
    #@TODO ta forloop bi lahko flashal postopoma
    for txt_file in request.files.getlist("file"):
            filename = secure_filename(txt_file.filename)
            # Is there really a file?
            if not filename:
                flash('There is no file. Try again?')
                return render_template("upload.html", username=username)
            
            lines = txt_file.readlines()
            links = [line.decode("UTF-8") for line in lines]
            import_list_of_links(links, user_id)



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



def import_list_of_links(list_of_links, user_id):
    #TODO nekak bi bilo dobro, da pokaže kateri so failali....
    for link in list_of_links:
        commit_link(link.strip(" ").strip("\n"), user_id)