# -*- coding: UTF-8 -*-
from enum import Enum
import json


class ErrorCode(Enum):
    # 基本错误码
    SUCCESS = 0
    FAILED = 1
    NOT_FOUND = 2
    ALREAY_EXIST = 3
    PARAMETER_ERROR = 4
    PENDING = 5
    INVALID_FUNC = 6
    INVALID_PARAMETERS = 7
    UNINIT = 8,
    NOT_SUPPORT = 9,
    NOT_UNIQUE = 10,
    NO_MORE_DATA = 11,

    # OCR识别和代码检测相关
    ANALYZE_REQ_ERROR = 50
    ANALYZE_GET_RESULT_REQ_ERROR = 51
    AZURE_REQUEST_TIMEOUT = 52
    AZURE_RUNNING = 53
    PARSE_RESULT_ERROR = 54
    DETECT_LANGUAGE_ERROR = 55
    DOWNLOAD_ERROR = 56

    # 数据库
    SQLITE_OPEN_FAILED = 100
    SQLITE_NOT_OPEN = 101
    SQLITE_QUERY_EXCEPT = 102

    def __str__(self):
        self.name.lower()

    @staticmethod
    def from_str(err):
        return ErrorCode[err.upper()]

    @staticmethod
    def internal_ret_2_http(ret):
        ret['err'] = ret['err'].name.lower()

    @staticmethod
    def http_ret_2_internal(ret):
        key = ret['err']
        if key == 'success':
            ret['err'] = ErrorCode.SUCCESS
        elif key == 'failed':
            ret['err'] = ErrorCode.FAILED
        elif key == 'not_found':
            ret['err'] = ErrorCode.NOT_FOUND
        elif key == 'already_exist':
            ret['err'] = ErrorCode.ALREAY_EXIST
        else:
            ret['err'] = ErrorCode.FAILED
        return ret


class ResultEnconding(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ErrorCode):
            return o.name.lower()


def dump_result(ret):
    print(json.dumps(ret, indent=2, ensure_ascii=False, cls=ResultEnconding))


def dump_result_2_file(file, ret):
    with open(file, 'w') as f:
        f.write(json.dumps(ret, indent=2,
                           ensure_ascii=False, cls=ResultEnconding))


if __name__ == "__main__":
    print(ErrorCode.SUCCESS.name.lower())
    print(ErrorCode.SUCCESS.value)
