"""

"""
import logging
import sys
from flask import Flask, Blueprint,render_template, send_from_directory,jsonify, url_for, abort
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
# Initialize application
app = Flask(__name__)
app.config['MAIL_SERVER']= "buran.htu.tuwien.ac.at"
app.config['MAIL_DEFAULT_SENDER']="andis@fet.at"
app.config['FREEZER_DESTINATION_IGNORE']=['*.zip',"intern"]
mail=Mail(app)
app.config["url_prefix"]=""
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)



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"]



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('/')
def index():
    return render_template("lva_liste.html", lvas=lvas,zip=False)

@page_blueprint.route('/intern/zips.html')
def indexzips():
    return render_template("lva_liste.html", lvas=lvas,zip=True)

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


@page_blueprint.route('intern/zips//<name>.zip')
def files(name):

    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'}
    
    

    
app.register_blueprint(page_blueprint, url_prefix=app.config["url_prefix"],static_folder='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)
