from Controller import OTAEquipment
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from django.utils.decorators import method_decorator
from Ansjer import local_settings as api_settings
from Service.ModelService import ModelService
import time,os
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Ansjer.config import BASE_DIR


def StatisticsData(request):
    print('------request------')

    print(request)
    print('---------------')
    try:
        real_ip = request.META['HTTP_X_FORWARDED_FOR']
        clientIP = real_ip.split(",")[0]
    except:
        try:
            clientIP = request.META['REMOTE_ADDR']
        except Exception as e:
            clientIP = ''

    nowTime = time.strftime('%Y-%m-%d', time.localtime(time.time()))

    print(u'当前用户: %s , 访问时间: %s' % (clientIP, nowTime))

    print(u'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    for cookKey, cookValue in request.COOKIES.items():
        print("COOKIES:", cookKey, cookValue)

    for sessionKey, sessionValue in request.session.items():
        print("session:", sessionKey, sessionValue)

    print('HTTP_COOKIE', request.META.get('HTTP_COOKIE', 'unknown'))
    print('CSRF_COOKIE', request.META.get('CSRF_COOKIE', 'unknown'))

    print('user', request.user)

    print(u'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')

    # print("body:", request.body)
    print('path', request.path)
    print('path_info', request.path_info)

    print('encoding', request.encoding)
    print('resolver_match', request.resolver_match)

    for fileKey, fileValue in request.FILES.items():
        print("FILES:", fileKey, fileValue)
    #print('META', request.META)

    print(u'******************************************************')
    print('DOCUMENT_ROOT', request.META.get('DOCUMENT_ROOT', 'unknown'))
    print('QUERY_STRING: ', request.META.get('QUERY_STRING', 'unknown'))
    print('REMOTE_ADDR', request.META.get('REMOTE_ADDR', 'unknown'))
    print('HTTP_HOST', request.META.get('HTTP_HOST', u'unknown'))
    print('HTTP_REFERER', request.META.get('HTTP_REFERER', 'unknown'))
    print('HTTP_COOKIE', request.META.get('HTTP_COOKIE', 'unknown'))
    print('CSRF_COOKIE', request.META.get('CSRF_COOKIE', 'unknown'))
    print('HTTP_CONNECTION', request.META.get('HTTP_CONNECTION', 'unknown'))
    print('wsgi.errors', request.META.get('wsgi.errors', 'unknown'))
    print('mod_wsgi.application_group', request.META.get('mod_wsgi.application_group', 'unknown'))
    print('mod_wsgi.callable_object', request.META.get('mod_wsgi.callable_object', 'unknown'))
    print('mod_wsgi.listener_host', request.META.get('mod_wsgi.listener_host', 'unknown'))
    print('mod_wsgi.listener_port', request.META.get('mod_wsgi.listener_port', 'unknown'))
    print('mod_wsgi.process_group', request.META.get('mod_wsgi.process_group', 'unknown'))
    print('mod_wsgi.reload_mechanism', request.META.get('mod_wsgi.reload_mechanism', 'unknown'))
    print('mod_wsgi.script_reloading', request.META.get('mod_wsgi.script_reloading', 'unknown'))
    print('mod_wsgi.version', request.META.get('mod_wsgi.version', 'unknown'))
    print('PATH', request.META.get('PATH', 'unknown'))
    print('PATH_INFO', request.META.get('PATH_INFO', 'unknown'))
    print('PATH_TRANSLATED', request.META.get('PATH_TRANSLATED', 'unknown'))
    print('QUERY_STRING', request.META.get('QUERY_STRING', 'unknown'))
    print('QUERY_STRING', request.META.get('REMOTE_ADDR', 'unknown'))
    print('REMOTE_PORT', request.META.get('REMOTE_PORT', 'unknown'))
    print('REQUEST_METHOD', request.META.get('REQUEST_METHOD', 'unknown'))
    print('REQUEST_URI', request.META.get('REQUEST_URI', 'unknown'))
    print('SCRIPT_FILENAME', request.META.get('SCRIPT_FILENAME', 'unknown'))
    print('SCRIPT_NAME', request.META.get('SCRIPT_NAME', 'unknown'))
    print('SERVER_ADDR', request.META.get('SERVER_ADDR', 'unknown'))
    print('SERVER_ADMIN', request.META.get('SERVER_ADMIN', 'unknown'))
    print('SERVER_NAME', request.META.get('SERVER_NAME', 'unknown'))
    print('SERVER_PORT', request.META.get('SERVER_PORT', 'unknown'))
    print('SERVER_PROTOCOL', request.META.get('SERVER_PROTOCOL', 'unknown'))
    print('SERVER_SIGNATURE', request.META.get('SERVER_SIGNATURE', 'unknown'))
    print('SERVER_SOFTWARE', request.META.get('SERVER_SOFTWARE', 'unknown'))
    print('wsgi.input', request.META.get('wsgi.input', 'unknown'))
    print('wsgi.multiprocess', request.META.get('wsgi.multiprocess', 'unknown'))
    print('wsgi.multithread', request.META.get('wsgi.multithread', 'unknown'))
    print('wsgi.run_once', request.META.get('wsgi.run_once', 'unknown'))
    print('wsgi.url_scheme', request.META.get('wsgi.url_scheme', 'unknown'))
    print('wsgi.version', request.META.get('wsgi.version', 'unknown'))
    print('get_host', request.get_host())
    print('get_full_path', request.get_full_path())
    print('build_absolute_uri', request.build_absolute_uri())
    print('is_secure', request.is_secure())
    print('is_ajax', request.is_ajax())
    print(u'******************************************************')

    print('CONTENT_LENGTH: ', request.META.get('CONTENT_LENGTH', 'unknown'))
    print('CONTENT_TYPE', request.META.get('CONTENT_TYPE', 'unknown'))
    print('HTTP_ACCEPT', request.META.get('HTTP_ACCEPT', 'unknown'))
    print('HTTP_ACCEPT_ENCODING', request.META.get('HTTP_ACCEPT_ENCODING', 'unknown'))
    print('REMOTE_HOST', request.META.get('REMOTE_HOST', 'unknown'))
    print('REMOTE_USER', request.META.get('REMOTE_USER', 'unknown'))
    print('REQUEST_METHOD', request.META.get('REQUEST_METHOD', 'unknown'))
    print('SERVER_NAME', request.META.get('SERVER_NAME', 'unknown'))
    print('SERVER_PORT', request.META.get('SERVER_PORT', 'unknown'))
    print('HTTP_USER_AGENT', request.META.get('HTTP_USER_AGENT', 'unknown'))
    print('HTTP_AUTHORIZATION', request.META.get('HTTP_AUTHORIZATION', b'unknown'))


class HelpView(TemplateView):
    '''
    帮助说明，包括版本信息，帮助文件等
    '''
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(HelpView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        reInfoType = request.GET.get('reInfoType', None)
        token = request.GET.get('token', None)

        return self.getRequestInfo(reInfoType,token)

    def post(self, request, *args, **kwargs):
        reInfoType = request.POST.get('reInfoType', None)
        token = request.POST.get('token', None)
        return self.getRequestInfo(reInfoType,token)

    def getRequestInfo(self, reInfoType,token):
        response = ResponseObject()
        if reInfoType is not None and token is not None:
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code == 0:
                userID = tko.userID
                own_permission = ModelService.check_perm(userID=userID, permID=30)
                if own_permission is True:
                    if reInfoType == 'version':
                        return self.readInfo(response)
                    elif reInfoType == 'requirements':
                        return self.requirementsInfo(response)
                    elif reInfoType == 'helpfile':
                        return self.getHelpCHM(response)
                    else:
                        return response.json(444)
                else:
                    return response.json(404)
            else:
                return response.json(tko.code)
        else:
            return response.json(800,'reInfoType','reInfoType')

    def readInfo(self,response):
        verfilePath = '/'.join((api_settings.BASE_DIR, 'static/Help/')).replace('\\', '/') + 'version.txt'
        if os.path.isfile(verfilePath):
            file = open(verfilePath, encoding='utf-8')
            versionStr = ''
            for line in file:
                versionStr += line
            return response.json(0,{'versioninfo':versionStr})
        else:
            return response.json(701)

    def requirementsInfo(self,response):
        requirementsPath = '/'.join((api_settings.BASE_DIR, 'requirements.txt')).replace('\\', '/')
        print(requirementsPath)
        if os.path.isfile(requirementsPath):
            file = open(requirementsPath, encoding='utf-8')
            requirementsStr = ''
            for line in file:
                requirementsStr += line
            return response.json(0,{'requirementsinfo': requirementsStr})
        else:
            return response.json(701)

    def getHelpCHM(self,response):
        verHelpCHM = '/'.join((api_settings.BASE_DIR, 'static/Help/')).replace('\\', '/') + 'AnsjerHelp.CHM'
        print(verHelpCHM)
        if os.path.isfile(verHelpCHM):
            return OTAEquipment.downloadUrl(fileType='CHM', fileCode='', fileVersion='', fileName=verHelpCHM)
        else:
            return response.json(code=701)


def upload_help_chm(request):
    token = request.POST.get('token', None)
    response = ResponseObject()
    if token is not None:
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code == 0:
            userID = tko.userID
            own_permission = ModelService.check_perm(userID=userID, permID=30)
            if own_permission is True:
                f = request.FILES.get('file', None)
                path = os.path.join(BASE_DIR, 'static/Help/AnsjerHelp.CHM')
                try:
                    if os.path.exists(path):
                        os.remove(path)
                    with open(path, 'wb+') as destination:
                        for chunk in f.chunks():
                            destination.write(chunk)
                except Exception as e:
                    print('error:' + repr(e))
                    return response.json(700,{'details': repr(e)})
                return response.json(0)
            else:
                return response.json(404)
        else:
            return response.json(tko.code)
    else:
        return response.json(309)

@csrf_exempt
def errorPath(request,**kwargs):
    response = ResponseObject()
    return response.json(414)