"""

"""
import logging
import sys
from flask import Flask, Blueprint,render_template, send_from_directory,jsonify,redirect, url_for, abort,flash
from flask_frozen import Freezer
from config import Config
import os
import re
from functools import partial
import yaml
import slugify
from flask_mail import Mail,Message
from zipfile import ZipFile
from .token import TokenCollection
from flask import request
from cachetools import TTLCache, cached
from werkzeug.utils import secure_filename
# Initialize application
app = Flask(__name__,static_url_path="/bsp/static")
app.config['MAIL_SERVER']= "buran.htu.tuwien.ac.at"
app.config['MAIL_DEFAULT_SENDER']="andis@fet.at"
app.config['FREEZER_DESTINATION_IGNORE']=['*.zip',"*intern*"]
app.config['FREEZER_STATIC_IGNORE']=['*.zip',"*intern*"]

mail=Mail(app)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.config["url_prefix"]="/bsp"
app.logger.setLevel(logging.DEBUG)
# Initialize FlatPages Index
tokens = TokenCollection("tokens.yaml")

#msg = Message("Hello",
#                  sender="andis@fet.at",
#                  recipients=["andis@fet.at"])

#mail.send(msg)
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@cached(cache=TTLCache(maxsize=1024, ttl=3600))
def load_lvas_folders_studien():
    lvas=[]
    studien={}
    #search the data directory for yaml files
    for base,_, files in os.walk("data"):
        for fn in files:
            if re.match(".*yaml$", fn):
                with open(os.path.join("data",fn),"r") as f:
                    data=yaml.load(f.read(),yaml.Loader)
                    studien[fn]=data


    #with open(os.path.join("test.yaml"),"w") as f:
    #    f.write(yaml.dump(studien))

# create a lva list from the structure
    for studium, lvaliste in studien.items():
        for k,lva in lvaliste.items():
            if len(lva)>3:
                lvas+=[lva]
    folders={}

    #with open(os.path.join("testlvaliste.yaml"),"w") as f:
    #    f.write(yaml.dump(lvas))
# make folders compact in lva
    for lva in lvas:
        for l in lva["courses"]:
            if "folders" in l:
                for folder in l["folders"]:
                    folders[folder["folder"]]= folder["folderpath"]

    return lvas, folders, studien

app.logger.info('Initialize FET BSP Sammlung')

freezer = Freezer(app)

page_blueprint  = Blueprint('bsp', __name__)
api_blueprint  = Blueprint('api', __name__)

@app.template_filter()
def slug(string):
    return slugify.slugify(string)

@app.template_filter()
def toyaml(obj):
    return yaml.dump(obj)

@page_blueprint.route('/sendmail.html')
def send_a_mail():
    msg = Message("Hello",
    sender="andis@fet.at",
    recipients=["andis@fet.at"])
    app.logger.info(msg)
    mail.send(msg)
    return "Done", 200

#@page_blueprint.route('/<path:name>/',strict_slashes=False)
@page_blueprint.route('/', methods=['GET', 'POST'])
def index():
    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 user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            folder=os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(request.form["lva"]))
            os.makedirs(folder)
            file.save(os.path.join(folder, filename))
            flash('Vielen Dank für deinen Upload')
            return redirect(request.url)
    lvas,folders,studien=load_lvas_folders_studien()
    return render_template("lva_liste.html", lvas=lvas,zip=False)


@page_blueprint.route('intern/index.html')
def indexzips():
    t=tokens.create()
    lvas,folders,studien=load_lvas_folders_studien()
    return render_template("lva_liste.html", lvas=lvas,zip=True, token=t)


@page_blueprint.route('zips//<name>.zip')
def files(name):
    lvas, folders =load_lvas_folders_studien()
    token = request.args.get('token')
    # create a ZipFile objec
    if not name in folders:
        app.log.error("Not found %s" % name)
        return "NotFound",404
    if not tokens.is_valid(token):
        return "Restricted",401

    with ZipFile("zips/%s.zip" % name, 'w') as zipObj:
   # Iterate over all the files in directory
     for folderName, subfolders, filenames in os.walk(folders[name]):
       for filename in filenames:
           #create complete filepath of file in directory
           filePath = os.path.join(folderName, filename)
           # Add file to zip
           zipObj.write(filePath, os.path.basename(filePath))
    return send_from_directory(os.path.abspath("zips"), "%s.zip" %  name)
       

@api_blueprint.route('/index.json',strict_slashes=False)
def api_index(name='index'):
    return jsonify(page={}), 200, {'Content-Type': 'application/json; charset=utf-8'}
    
    
@freezer.register_generator
def url_freeze():
    yield "/"
    
app.register_blueprint(page_blueprint, url_prefix=app.config["url_prefix"],static_folder='static',static_url_path="bsp/static")
app.register_blueprint(api_blueprint, url_prefix=app.config["url_prefix"]+"/api/",static_folder='static')
#app.add_url_rule('%s/<path:name>' % cfg.url_prefix,'page', post)
