#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from django.views.generic.base import View, TemplateView

from model.models import UserModel, LangProjectModel
from object.ResponseObject import ResponseObject
from object.TokenObject import TokenObject


class LangProjectView(TemplateView):

    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 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 validate(self, request_dict, operation):
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            userID = tko.userID
            user_qs = UserModel.objects.filter(id=userID, username='admin')
            if not user_qs.exists():
                return response.json(403)

        if operation == 'query':
            return self.do_query(request_dict, response)
        else:
            return response.json(403)

    def do_query(self, request_dict, response):
        lp_qs = LangProjectModel.objects.filter().values()
        return response.json(0, list(lp_qs))
