from django.views import View
from Object.ResponseObject import ResponseObject
from Model.models import OperatingLogsModel
from Controller.ProcessInfo import ProcessInfoView
from Object.TokenObject import TokenObject
from Object.LogsObject import LogsObject

class OperatingLogsView(View):
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        operation = kwargs.get('operation', None)
        return self.validate(request_dict, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.POST
        operation = kwargs.get('operation', None)
        return self.validate(request_dict, operation)

    def validate(self, request_dict, operation):
        response = LogsObject()
        # token = request_dict.get('token', None)
        # tko = TokenObject(token)

        if operation is None:
            return response.json(444, 'error path')
        elif operation == 'add_logs':
            return self.add_logs(request_dict, response)
        elif operation == 'delete_logs':
            return self.delete_logs(request_dict, response)

    def add_logs(self, request_dict, response):
        d = self.get_info(request_dict)
        if(d['userId'] == ''):
            return response.json(908)
        OperatingLogsModel.objects.create(
            userId=d['userId'],
            operatingcontent=d['operatingcontent'],
            operatingtype=d['operatingtype'],
            is_saveprocessinfo=d['is_saveprocessinfo'],
            devUid=d['devUid'],
            userIp=d['userIp'],
        )
        if d['is_saveprocessinfo'] == '1':
            ProcessInfoView.validate(ProcessInfoView(), request_dict, 'add_processinfo')
        return response.json(0)

    def delete_logs(self, request_dict, response):
        userId = request_dict.get('userId', None)
        if userId:
            OperatingLogsModel.objects.filter(userId=userId).delete()
            return response.json(0)
        else:
            return response.json(444, 'userId is not exist')


    def get_info(self, request_dict):
        userId = request_dict.get('userId', None)
        operatingcontent = request_dict.get('operatingcontent', None)
        operatingtype = request_dict.get('operatingtype', None)
        is_saveprocessinfo = request_dict.get('is_saveprocessinfo', None)
        devUid = request_dict.get('devUid', None)
        userIp = request_dict.get('userIp', None)
        return {
            'userId': userId,
            'operatingcontent': operatingcontent,
            'operatingtype': operatingtype,
            'is_saveprocessinfo': is_saveprocessinfo,
            'devUid': devUid,
            'userIp': userIp,
        }





