# -*- coding: utf-8 -*-

import os
import re
from random import Random  # 用于生成随机码
from wsgiref.util import FileWrapper

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from Ansjer.config import BASE_DIR
from Object.ResponseObject import ResponseObject


# 生成随机字符串
def RandomStr(randomlength=8, number=False):
    str = ''
    if number == False:
        characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
                       'tUuVvWwXxYyZz0123456789'
    else:
        characterSet = '0123456789'

    length = len(characterSet) - 1

    random = Random()
    for index in range(randomlength):
        str += characterSet[random.randint(0, length)]

    return str


def date_handler(obj):
    return obj.isoformat()


class DataValid:

    def __init__(self):
        # 用户名正则
        # self.re_name = re.compile(r'^[A-Za-z0-9\u4e00-\u9fa5\.\_]{1,16}$')
        self.re_name = re.compile(r'^[A-Za-z0-9\u4e00-\u9fa5\.\_\-\@]{4,64}$')
        # 密码强度正则
        self.re_password = re.compile(r'^[\w\.\_\@\-]{1,16}$')
        # 手机号码正则
        self.re_mobile = re.compile(r'^\d{1,16}$')
        # 邮箱地址正则
        self.re_email = re.compile(r'^[A-Za-z0-9\u4e00-\u9fa5\.\_\-]+@[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)+$')

    def name_validate(self, value):
        if self.re_name.match(value):
            return True
        else:
            return False

    def password_validate(self, value):
        if self.re_password.match(value):
            return True
        else:
            return False

    def email_validate(self, value):
        if self.re_email.match(value):
            return True
        else:
            return False

    def mobile_validate(self, value):
        if self.re_mobile.match(value):
            return True
        else:
            return False


@csrf_exempt
def download_file(request, Upgradename, *callback_args, **callback_kwargs):
    """
    下载单个文件
    :param request:
    :param Upgradename:
    :param callback_args:
    :param callback_kwargs:
    :return:
    """
    print(Upgradename)
    print(callback_args, callback_kwargs)
    for value in callback_args:
        print("other args:", value)
    # 打印dict类型的不定长参数 args
    for key in callback_kwargs:
        print("dictargs:" + key + ":" + bytes(callback_kwargs[key]))
    print(request.body)
    file_name = os.path.join(BASE_DIR, "static/Upgrade/DVR/").replace('\\', '/') + Upgradename
    response = ResponseObject()
    if os.path.isfile(file_name):
        try:
            print(file_name)
            JSON = response.formal(0)
            wrapper = FileWrapper(open(file_name, 'rb'))
            response = HttpResponse(wrapper, content_type="application/octet-stream")
            response['Content-Length'] = os.path.getsize(file_name)
            response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(file_name)
            response['Content-Error'] = JSON
            return response
        except Exception as e:
            errorJSON = response.formal(10, 'Wrong reason:' + repr(e))
            response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
            response['Content-Error'] = errorJSON
            return response
    else:
        errorJSON = response.formal(907)
        response = HttpResponse(errorJSON, content_type='text/plain', charset='utf-8')
        response['Content-Error'] = errorJSON
        return response
