#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time

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):
        token = TokenObject(request_dict.get('token', None))

        response = ResponseObject()

        if token.code != 0:
            return response.json(token.code)

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

    def do_initUserRegion(self, userID, request_dict, response):
        user = Device_User.objects.get(userID=userID)
        number = request_dict.get('number', None)
        if not user:
            return response.json(309)

        user.region_country=number
        user.save()
        return response.json(0)
