import logging

from flask import request, json
from werkzeug.exceptions import HTTPException



class APIException(HTTPException):
    message = 'sorry, we made a mistake (*￣︶￣)!'
    code=200
    def __init__(self, message=None, code=None,
                 headers=None, **kwargs):
        if code:
            self.code = code
        if message:
            self.message = message
        self.kwargs = kwargs
        super(APIException, self).__init__(message,None)

    def get_body(self,environ=None, code=None):
        body = dict(
            message=self.message,
            code=self.code,
        )
        text = json.dumps(body)
        return text

    def get_headers(self,environ=None, code=None):
        """Get a list of headers."""
        return [('Content-Type', 'application/json')]

    @staticmethod
    def get_url_no_param():
        full_path = str(request.full_path)
        main_path = full_path.split('?')
        return main_path[0]


class ViewException(Exception):
    """view错误基类"""

    def __init__(self, error_code: int, code: int = 200, message='', **kwargs):
        self.error_code = error_code
        self.code = code
        self.message = message
        self.kwargs = kwargs

    @property
    def info(self):
        """请求相关信息"""
        return {'code': self.code, 'error_code': self.error_code, 'message': self.message, **self.kwargs}


class FormException(ViewException):
    """表单验证错误"""

    @property
    def info(self):
        """表单错误信息"""
        return {'code': self.code, 'error_code': self.error_code, 'message': self.message, **self.kwargs}


class Success(APIException):
    message = 'ok'
    error_code = 0


class ServerError(APIException):
    message = 'sorry, we made a mistake (*￣︶￣)!'
    error_code = 999


class AuthFailed(APIException):
    error_code = 1005
    message = 'token不正确'


class Forbidden(APIException):
    error_code = 1004
    message = '地址已变请重新登录'


class NotFound(APIException):
    message = 'the resource are not found O__O...'
    error_code = 1001

    @property
    def info(self):
        """表单错误信息"""
        return {'code': self.code, 'error_code': self.error_code, 'message': self.message, **self.kwargs}


class ParameterException(APIException):
    message = 'invalid parameter'
    error_code = 1000


class ErrorMessage(APIException):
    message = '操作错误...'
    error_code = 1008


class ErrorWxMessage(APIException):
    message = 'ticket cache null...'
    error_code = 1009


class ErrorEndpoint(APIException):
    message = 'Endpoint  No Access'
    error_code = 1010

class ErrorTimeout(APIException):
    message = '登录过期,请重新登录'
    error_code = 1010

class SignatureFalse(APIException):
    message = '验证失败'
    error_code = 1010

