from requests import get

from BaseLib.BaseView import BaseView
from Platform import settings


class VKAuthView(BaseView):
    required_login = True
    endpoint = "vk_auth"
    view_file = "vk_auth.html"
    fields_except = ('user_id',)

    def get(self):
        access_token = self.request.GET.get('access_token')
        if access_token is None:
            if self.request.GET.get("error") == "access_denied":
                return "/profile"
            return
        token = settings.VK_SERVICE_TOKEN
        resp = get(f'https://api.vk.com/method/secure.checkToken?token={access_token}&access_token={token}&v=5.131').json()
        print(resp)
        if 'response' in resp and 'success' in resp['response'] and resp['response']['success'] == 1:
            user_id = resp['response']['user_id']
            resp = get(f'https://api.vk.com/method/users.get?access_token={token}&user_ids={user_id}&v=5.131',
                       headers={"accept-language": "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7"})
            if resp.status_code != 200:
                return "/profile"
            data = resp.json()['response'][0]
            self.request.user.vk_id = data['id']
            self.request.user.save()
        return "/profile"
