"""
Paramecio2fm is a series of wrappers for Flask, mako and others and construct a simple headless cms.

Copyright (C) 2023 Antonio de la Rosa Caballero

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

from flask import Flask, session, url_for, request, send_file, abort
from settings import config
from importlib import import_module
import os
import sys
import inspect
from paramecio2.libraries.datetime import set_timezone

def start_app():
    
    set_timezone()
    
    app=Flask(__name__, static_url_path=config.static_url_path, static_folder=config.static_folder)

    app.secret_key=config.secret_key

    try:
        app.json.sort_keys=False

    except:
        
        app.config['JSON_SORT_KEYS']=False

    application_root='/'

    if hasattr(config, 'application_root'):
        #print(config.application_root)
        application_root=config.application_root

    
    app.config.update(
         APPLICATION_ROOT=application_root
    )
    
    #app.config['APPLICATION_ROOT']=application_root

    if hasattr(config, 'json_sort_keys'):
        app.config.update(
            JSON_SORT_KEYS=config.json_sort_keys
        )
        
    if hasattr(config, 'server_name'):
        app.config.update(
            SERVER_NAME=config.server_name
        )

    workdir=os.getcwd()
    arr_module_path={}

    # Load blueprints
    
    for key_app, added_app in config.apps.items():

        controller_path=import_module(added_app[0])
        
        controller_base=os.path.dirname(controller_path.__file__)
        
        dir_controllers=os.listdir(controller_base)
        
        app_name=getattr(controller_path, added_app[1])
        
        for controller in dir_controllers:
                
            if controller.find('.py')!=-1 and controller.find('__init__')==-1:
                    
                controller_py=controller.replace('.py', '')
                
                module_app=added_app[0]+'.'+controller_py
                
                a=import_module(module_app)
                
                arr_module_path[key_app]=os.path.dirname(sys.modules[module_app].__file__)
        if config.application_root=='/':
            app.register_blueprint(app_name, url_prefix=added_app[2])
        else:
            app.register_blueprint(app_name, url_prefix=config.application_root+added_app[2][1:])
    """
        module_app=config.apps[added_app][0]
        
        a=import_module(module_app)
        #print(added_app, file=sys.stdout)
        app_name=getattr(a, config.apps[added_app][1])

        app.register_blueprint(app_name, url_prefix=config.apps[added_app][2])
        
        arr_module_path[added_app]=os.path.dirname(sys.modules[module_app].__file__)
    """

    #Add media files support. Only for development. 
    
    @app.route(config.application_root+'mediafrom/<module>/<path:media_file>')
    def send_media_file(module, media_file):
        
        file_path=workdir+'/themes/'+config.theme+'/media/'+module+'/'+media_file
    
        if not os.path.isfile(file_path):
            #file_path=workdir+'/modules/'+module+'/media/'+media_file
            file_path=arr_module_path[module]+'/media/'+media_file

            if not os.path.isfile(file_path):
                abort(404)
                
        return send_file(file_path)

    return app
