import os
import sys

from json import JSONEncoder

from werkzeug.utils import secure_filename
from flask import (
    Flask,
    g,
    render_template,
    jsonify,
    request,
    redirect,
    url_for
)
from waitress import serve
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_wtf.csrf import CSRFProtect, CSRFError
from flask_moment import Moment

from models import db, lm
from mailsender import mail

sys.stderr.write("worker uid={} gid={}".format(os.getuid(), os.getgid()))
sys.stderr.flush()

app = Flask(__name__)
app.config.from_object("config.Config")

db.init_app(app)
lm.init_app(app)

mail.init_app(app)

bootstrap = Bootstrap()
bootstrap.init_app(app)

csrf = CSRFProtect(app)
#csrf.init_app(app)

moment = Moment(app)
moment.init_app(app)

from main import main as main_blueprint
app.register_blueprint(main_blueprint)

from panel import panel as panel_blueprint
app.register_blueprint(panel_blueprint, url_prefix='/panel')

from auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')

from admin import admin as admin_blueprint
app.register_blueprint(admin_blueprint, url_prefix='/' + app.config['ADMIN_PREFIX'])

from settings import settings as settings_blueprint
app.register_blueprint(settings_blueprint, url_prefix='/settings')

@app.errorhandler(403)
def forbidden(e):
    if request.accept_mimetypes.accept_json and \
            not request.accept_mimetypes.accept_html:
        response = jsonify({'error': 'forbidden'})
        response.status_code = 403
        return response
    return render_template('errors/403.html'), 403

@app.errorhandler(404)
def page_not_found(e):
    if request.accept_mimetypes.accept_json and \
            not request.accept_mimetypes.accept_html:
        response = jsonify({'error': 'not found'})
        response.status_code = 404
        return response
    return render_template('errors/404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
    if request.accept_mimetypes.accept_json and \
            not request.accept_mimetypes.accept_html:
        response = jsonify({'error': 'internal server error'})
        response.status_code = 500
        return response
    return render_template('errors/500.html'), 500

@app.errorhandler(503)
def service_unavailable(e):
    if request.accept_mimetypes.accept_json and \
            not request.accept_mimetypes.accept_html:
        response = jsonify({'error': 'service unavailable'})
        response.status_code = 503
        return response
    return render_template('errors/503.html'), 503

@app.errorhandler(CSRFError)
def handle_csrf_error(e):
    return render_template('errors/csrf_error.html', reason=e.description), 400

if __name__ == "__main__":
    serve(app, listen='*:5000')
