from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from allauth.account.utils import user_field
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
import requests
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile

class MyAccountAdapter(DefaultAccountAdapter):

    def get_login_redirect_url(self, request):
        path = super(MyAccountAdapter, self).get_login_redirect_url(request)

        try:
            user = request.user
            user_profile = user.user_profile
            if user_profile and not user_profile.avatar:
                social_accounts = user.socialaccount_set.all()
                if social_accounts:
                    for social_account in social_accounts:
                        if 'picture' in social_account.extra_data and social_account.extra_data['picture']:
                            r = requests.get(social_account.extra_data['picture'])

                            img_temp = NamedTemporaryFile()
                            img_temp.write(r.content)
                            img_temp.flush()
                            user_profile.avatar.save(f'avatar_{user.id}.jpeg', File(img_temp), True)
                            break

        except Exception as e:
            msg = f'post_save create_user_profile Error = {str(e)}'
            print(msg)

        return path

# class CustomSocialAccountAdapter(DefaultSocialAccountAdapter):
#     def populate_user(self, request, sociallogin, data):
#         from AuthApp.models import UserProfile
#
#         user = super().populate_user(request, sociallogin, data)
#         try:
#             picture = sociallogin.account.extra_data['picture']
#             user_profile = UserProfile.objects.get_or_create(user=user)
#             with open(picture, 'rb') as fd:
#                 user_profile.avatar.save(f'user_{user.id}_avatar.jpeg', fd.read(), True)
#             # user_field(user, "profile_photo", picture)
#         except Exception as e:
#             msg = f'CustomSocialAccountAdapter populate_user Error = {str(e)}'
#             print(msg)
#
#         return user