'''
Author: your name
Date: 2021-04-14 14:12:18
LastEditTime: 2021-06-29 19:37:32
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\backend\view\__init__.py
'''
#!/usr/bin/env python
# -*- coding: utf_8 -*-

import logging
import traceback
from flask import Flask, Response, jsonify
from flask_cors import CORS
from werkzeug.exceptions import HTTPException, InternalServerError
from .api import api
from .files import file_api
from .login import login_api
from .user import user_api
from .annex import annex_api
from .apps import apps_api
from .device import device_api
from .download import download_api
from .app_logs import appLogs_api
from model import fullStackDB
from fullstack.response import ResponseCode, response_result
from app import config

logger = logging.getLogger(__name__)

class JsonResponse(Response):
    @classmethod
    def force_type(cls, response, environ=None):
        if isinstance(response, (list, dict)):
            response = jsonify(response)
        return super(cls, Response).force_type(response, environ)

class FlaskAPP(Flask):
    response_class = JsonResponse

    def unauthorized(self, message):
        return response_result(ResponseCode.AUTHORIZATION_ERROR, msg=message)

def create_app():
    app = FlaskAPP(__name__)
    app.register_blueprint(api)
    app.register_blueprint(login_api)
    app.register_blueprint(file_api)
    app.register_blueprint(user_api)
    app.register_blueprint(annex_api)
    app.register_blueprint(apps_api)
    app.register_blueprint(download_api)
    app.register_blueprint(device_api)
    app.register_blueprint(appLogs_api)

    @app.errorhandler(InternalServerError)
    def handle_500(e):
        logger.error(str(e))
        traceback.print_exc()
        return response_result(ResponseCode.SERVER_ERROR, msg=str(e))

    @app.errorhandler(HTTPException)
    def handle_http_exception(e):
        logger.error(str(e))
        traceback.print_exc()
        return response_result(ResponseCode.SERVER_ERROR, msg=str(e))

    @app.errorhandler(Exception)
    def handle_exception(e):
        logger.error(str(e))
        traceback.print_exc()
        return response_result(ResponseCode.SERVER_ERROR, msg=str(e))

    CORS(app, supports_credentials=True, origins='*')
    app.config.update(config)
    fullStackDB(app, drop_tables=[])

    return app

app = create_app()
