# coding=utf-8
from json import dumps, loads
import datetime
from flask import Flask, request, session, render_template, redirect, url_for, jsonify

from .modules.eeg_python_utils import utils, flask_utils
from .modules import errors
from .modules import flask_shared

application = Flask(__name__)
application.config.from_object(__name__)
application.secret_key = flask_shared.SECRET_KEY

application.jinja_env.globals.update(utcnow=datetime.datetime.utcnow)
application.jinja_env.filters['from_json'] = loads
application.jinja_env.filters['to_json'] = dumps
application.jinja_env.filters['from_timestamp'] = datetime.datetime.utcfromtimestamp
application.jinja_env.filters['nospace'] = lambda x: x.replace(" ", "")
application.jinja_env.filters['to_pretty_json'] = lambda x: dumps(x, sort_keys=True, indent=4, separators=(',', ': '))

application.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False
application.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 * 1024

application.debug = False

###################################################################
@application.route('/', methods=['GET'])
def home():
    print('redirect dashboard')
    return redirect(url_for('show_dashboard'))


@application.route('/icap/<path:path>', methods=['GET'])
@application.route('/lexi/<path:path>', methods=['GET'])
@application.route('/system/<path:path>', methods=['GET'])
@application.route('/<path:path>')
@application.route('/dashboard', methods=['GET'])
# @flask_utils.requires_login
def show_dashboard(*args, **kwargs):
    # print('show dashboard', session)
    username = flask_utils.get_username()
    # print('show dashboard', username)
    context = {
        'username': username
    }
    # print('context: {}'.format(dumps(context, indent=2)))
    return render_template('index.html', **context)


@application.route('/logout', methods=['GET'])
def logout():
    session['username'] = ''
    session.clear()
    print(f'session: {session}')
    return redirect(url_for('show_dashboard'))


@application.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        payload = utils.get_payload(request)
        # print('login: {}'.format(utils.jformat(payload)))
        username = payload.get('username')
        password = payload.get('password')
        if not username or not password:
            errors.not_authorized('Please enter a valid username and password')

        if username.strip() == '' or password.strip == '':
            errors.not_authorized('Please enter a valid username and password')

        # print('username', username)
        # print('password', password)

        flask_shared.authenticate_user(username, password)

        session['username'] = username
        # print('login session', session)
        return jsonify({'username': username}), 201


def error_response(e):
    print(e)
    # traceback.print_stack(limit=5)
    error = e.description or e
    print(str(error))
    return jsonify({'error': str(error)})


@application.errorhandler(400)
def bad_request(e):
    return error_response(e), 400


@application.errorhandler(401)
def not_authorized(e):
    return error_response(e), 401


@application.errorhandler(404)
def page_not_found(e):
    return error_response(e), 404


@application.errorhandler(403)
def forbidden(e):
    return error_response(e), 403


@application.errorhandler(410)
def gone(e):
    return error_response(e), 410


@application.errorhandler(422)
def unprocessable(e):
    return error_response(e), 422


@application.errorhandler(423)
def locked(e):
    return error_response(e), 423


@application.errorhandler(500)
def internal_error(e):
    return error_response(e), 500


@application.errorhandler(503)
def unavailable(e):
    return error_response(e), 503
