from django.views import View
from Model.models import Device_User
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject


class RegionCountryView(View):

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

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

    def validate(self, request_dict, operation):
        response = ResponseObject()
        token = TokenObject(request_dict.get('token', None))
        if token.code != 0:
            return response.json(token.code)

        if operation == 'initUserRegion':
            return self.init_user_region(token.userID, request_dict, response)
        else:
            return response.json(414)

    @staticmethod
    def init_user_region(user_id, request_dict, response):
        """
        初始化用户地区
        @param user_id: 用户id
        @param request_dict: 请求数据
        @request_dict number: 国家id
        @param response: 响应
        @return: response
        """
        region_country = request_dict.get('number', None)
        if not region_country:
            return response.json(444)

        device_user_qs = Device_User.objects.filter(userID=user_id)
        if not device_user_qs.exists():
            return response.json(104)

        device_user_qs.update(region_country=region_country, region_status=True)
        return response.json(0)
