from django.db import models


class OAuth2TokenManager(models.Manager):
    def update_or_create_token(self, token_data, user):

        query = self.filter(user=user)
        token_properties = {
            'token_type': token_data['token_type'],
            'access_token': token_data['access_token'],
            'refresh_token': token_data['refresh_token'],
            'expires_at': token_data['expires_at'],
        }

        if query.exists():
            return query.update(**token_properties)
        else:
            return self._create_oauthtoken(user, token_properties)

    def _create_oauthtoken(self, user, token_properties):
        token = self.create(user=user, **token_properties)
        return token

