from flask import Flask, g
from flask.json import JSONEncoder
from flask_sqlalchemy import SQLAlchemy
# from werkzeug.contrib.fixers import ProxyFix

# ------- import mods ------------------
from mods.db import init_db_engine
from mods.utils.logger import init_logger

# ------- regist custom json encoder  ------------------
import json
from enum import Enum


class DFJsonEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Enum):
            return str(obj)
        else:
            try:
                iterable = iter(obj)
            except TypeError:
                pass
            else:
                return list(iterable)
        return JSONEncoder.default(self, obj)


# ------- Flask Application  ------------------

app = Flask(__name__)
already_init = False


def init_app(config_object):
    global already_init
    if already_init:
        print('[Warning] App initialization has been requested multiple times.')
        return
    else:
        already_init = True
    app.config.from_object(config_object)

    app.json_encoder = DFJsonEncoder

    # for Reverse Proxy  # TODO Werkzeug 버전이 올라감에 따라 적용 방식이 바뀜
    # if app.config.get('ENABLE_PROXY_FIX'):
    #     app.wsgi_app = ProxyFix(app.wsgi_app)

    # ------- database engine ------------------
    if not app.config['TESTING']:
        init_db_engine(SQLAlchemy(app))

    # ------- Logging ------------------
    if not app.config['TESTING'] and not app.config['DEBUG']:
        init_logger(app.config['APPNAME'], app.config['LOG_LEVEL'], app.config['LOG_DIR'], app.config['LOG_FILE'])
    else:
        init_logger(app.config['APPNAME'], app.config['LOG_LEVEL'])

    # ------- common callback and handler ------------------

    return app


# ------- register controller ------------------
from web.main.controllers import main_controller
