from django.core.management.base import BaseCommand
from django.db import connections
from social_django.models import UserSocialAuth
from establishment.management.commands.add_position import namedtuplefetchall
from account.models import User


class Command(BaseCommand):
    help = '''Add account social networks from old db to new db. 
              Run after add_account!!!'''

    def social_sql(self):
        with connections['legacy'].cursor() as cursor:
            cursor.execute('''
                                select 
                                    DISTINCT
                                    i.account_id, i.provider, i.uid 
                                from 
                                (
                                    select a.email, a.id as account_id
                                    from accounts as a 
                                    where a.email is not null
                                ) t
                                join identities i on i.account_id = t.account_id	
            ''')
            return namedtuplefetchall(cursor)

    def handle(self, *args, **kwargs):
        objects = []
        for s in self.social_sql():
            user = User.objects.filter(old_id=s.account_id)
            if user.count() > 0:
                social = UserSocialAuth.objects.filter(user=user.first(),
                                                       provider=s.provider,
                                                       uid=s.uid)
                if social.count() == 0:
                    objects.append(UserSocialAuth(user=user.first(), provider=s.provider,
                                                  uid=s.uid)
                                   )

        UserSocialAuth.objects.bulk_create(objects)
        self.stdout.write(self.style.WARNING(f'Created social objects.'))