from flask import Flask, render_template, request, redirect, url_for
import frontmatter
import os
import mwclient
from dotenv import load_dotenv
load_dotenv()

from glob import glob

from werkzeug.utils import secure_filename


UPLOAD_FOLDER = 'static/upload'
ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'gif'}



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

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route("/", methods=["GET", "POST"])
def diary():

    if request.method=="POST":

        # 1. Connect to the Mediawiki client logging in as a user
        site = mwclient.Site('habitattt.it', path='/wiki/')
        site.login(
            username= os.environ.get('MEDIAWIKIBOT'),
            password= os.environ.get('MEDIAWIKIKEY')
        )


        date=request.form.get("date")
        title=request.form.get("title")
        memory=request.form.get("memory")
        filename=""
        wikimg=""

        if request.files: 
            file = request.files['file']
        # If the user does not select a file, the browser submits an
        # empty file without a filename.
       
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

                #allow the upload on the wiki from the .html form
                site.upload(file, filename, title)
                wikimg = '[[File:'+filename+']]'

        # Post as saving an .md file collecting the inputs
        post=frontmatter.Post(memory, title=title, date=date, file=filename)
        with open (f'submitted/{date}_{secure_filename(title)}.md', "w") as f:
            f.write(frontmatter.dumps(post))

        # Post as creating a Wiki Page

        # 2. Get a page to edit. If it doesn't exist it will be created
        page = site.pages[f'{date}']

        # 3. Get the text from the page
        text = page.text()

        # 4. Edit the contents
        text += f'== {date} == \n{memory} <br><br> {wikimg}'


        # 5. Write the modification
        page.edit(text, title)
        

        return redirect (url_for("diary"))

    memories=[]
    files=glob("./submitted/*.md")

    for file in files:
        with open(file, "r") as f:
            metadata, contents= frontmatter.parse(f.read())

            memory={"contents":contents, **metadata}
            memories.append(memory)

    memories.sort(key=lambda x: x['date'], reverse=True)
    return render_template("diary.html", memories=memories)

    


app.run(port=3146, debug=True)
