# Imports
from flask import Blueprint, render_template, abort
import os, markdown


# Create blueprint
bp = Blueprint('dynamic_routes', __name__)
template_folder = "templates"


# helper func
def get_path(file) -> str:
    return os.path.join(template_folder, "pages", file)


# Get all files in folder
def ListFiles(path):
    path = get_path(path)
    files = []
    for root, dirs, files_in_dir in os.walk(path):
        for file in files_in_dir:
            files.append(os.path.relpath(os.path.join(root, file), path))
        for dir in dirs:
            files.append(os.path.relpath(os.path.join(root, dir), path) + '/')
    return files


# Catch-all route for generic pages
@bp.route('/<path:filename>')
def catch_all(filename):
    if os.path.exists(get_path(filename)):
        if os.path.isdir(get_path(filename)):
            return render_template(
                'bases/directory.html',
                directory=filename + "/" if not filename.endswith('/') else filename,
                pages=ListFiles(filename)
            )
        
        return render_template(f'pages/{filename}')

    elif os.path.exists(get_path(filename + '.html')):
        return render_template(f'pages/{filename}.html')

    elif os.path.exists(get_path(filename + '.md')):
        output = markdown.markdown(open(get_path(filename + '.md'), "r").read())
        return render_template(
            f'bases/md.html',
            title = filename.split("/")[-1],
            markdown = output
        )

    else:
        abort(404, f"'{filename}' not found")