#!/usr/bin/env python
# -*- coding: utf_8 -*-
import logging
import traceback
from flask import Blueprint, request, redirect, url_for, json, Response
from app import config, signalManager
from fullstack.login import Auth
from fullstack.validation import validate_schema
from fullstack.response import ResponseCode, response_result
from schema.login import LoginSchema, RegisterSchema

logger = logging.getLogger(__name__)

login_api = Blueprint("login_api", __name__, url_prefix="/api/v1/%s/login" % config['NAME'])


@login_api.route("/", methods=['GET'])
def index():
    return redirect(url_for('/'))


@login_api.route("/login", methods=['POST'])
@validate_schema(LoginSchema)
def login():
    '''
    用户登录
    data: { "username": "xx", "password": "xx" }
    '''

    try:
        result, message = signalManager.actionLogin.emit(request.schema_data)
        if result:
            return response_result(message, data=result)
        else:
            return response_result(message)
    except Exception as e:
        traceback.format_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR, msg=str(e))


@login_api.route('/logout', methods=['POST'])
@Auth.auth_required
def logout():
    '''
    用户登出
    '''

    try:
        isSuccess, message = signalManager.actionLogout.emit()
        if isSuccess:
            return response_result(ResponseCode.OK, msg=message)
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.format_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR, msg=str(e))


@login_api.route('/register', methods=['POST'])
@validate_schema(RegisterSchema)
def register():
    '''
    用户注册
    '''

    try:
        isSuccess, message = signalManager.actionRegister.emit(request.schema_data)
        if isSuccess:
            return response_result(ResponseCode.OK, msg=message)
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.format_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR, msg=str(e))
