from django.contrib.auth import login
from requests import post, get

from BaseLib.BaseView import BaseView
from Platform import settings
from web.models import CustomUser


class YandexAuthView(BaseView):
    endpoint = "yandex_auth"

    def get(self):
        code = self.request.GET['code']
        response = post('https://oauth.yandex.ru/token', data={
            'client_id': '38f1906e99de4810bd79828f420ba885',
            'client_secret': settings.YANDEX_SERVICE_TOKEN,
            'grant_type': 'authorization_code',
            'code': code
        })
        if response.status_code != 200:
            print("Cant access, json: " + str(response.json()))
            return '/welcome'
        access_token = response.json().get('access_token')
        if access_token is None:
            print('no access token')
            return '/welcome'
        info_response = get('https://login.yandex.ru/info', headers={
            'Authorization': f'OAuth {access_token}'
        })
        if info_response.status_code != 200:
            print("Cant access, json: " + str(response.json()))
            return '/welcome'
        data = info_response.json()
        yandex_id = data['id']
        if self.request.user.is_authenticated:
            print('Got yandex_id writing to db ' + str(yandex_id))
            self.request.user.yandex_id = yandex_id
            self.request.user.save()
        else:
            print('Got yandex_id logging in' + str(yandex_id))
            user = CustomUser.objects.filter(yandex_id=yandex_id).first()
            if user is not None:
                login(self.request, user)
        return '/profile'
