from flask import Flask, render_template, url_for, request, flash, redirect, session
from functools import wraps
import os
from pathlib import Path, PurePath, PurePosixPath

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'username' not in session:
            return redirect(url_for('login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function

def init_app(config):

    if 'USERS_FOLDER' in config.keys():
        users_folder = config['USERS_FOLDER']
    else:
        print ("L'application n'est pas configuré correctement, veuillez renseigner les paramètres USERS_FOLDER et/ou PUBLIC_FOLDER ne sont pas configuré")
        return False
    
    if os.path.isdir(users_folder):
        print("Le dossier {} existe".format(users_folder))
    else:
        os.makedirs(users_folder)
        print("Le dossier {} a été créé".format(users_folder))        

    
    return True


def list_type_blocs(theme):

    type_blocs = list()

    blocs_list = Path(PurePosixPath('app').joinpath('templates','themes', theme, 'blocs'))
    for bloc_type in blocs_list.iterdir():
        if not(bloc_type.is_dir()):
            name_bloc=bloc_type.name.split('.')[0]
            type_blocs.append(name_bloc[1:])
    
    return type_blocs

def list_type_pages(theme):

    type_pages = list()

    pages_list = Path(PurePosixPath('app').joinpath('templates','themes', theme, 'pages'))
    for page_type in pages_list.iterdir():
        if not(page_type.is_dir()):
            name_page=page_type.name.split('.')[0]
            type_pages.append(name_page)
    
    return type_pages



