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


class Command(BaseCommand):
    help = 'Update accounts image from old db to new db'

    def account_sql(self):
        with connections['legacy'].cursor() as cursor:
            cursor.execute('''
                                select	
                                       url as image_url,
                                       t.account_id
                                from 
                                (
                                    select a.account_id,  a.attachment_file_name,  
                                           trim(CONCAT(u.url, a.attachment_suffix_url))  as url 
                                    from account_pictures a, 
                                    (select  'https://s3.eu-central-1.amazonaws.com/gm-test.com/media/' as url) u  
                                ) t  
                            ''')
            return namedtuplefetchall(cursor)

    def handle(self,  *args, **kwargs):
        for a in self.account_sql():
            users = User.objects.filter(old_id=a.account_id)
            users.update(image_url= a.image_url)
        self.stdout.write(self.style.WARNING(f'Update accounts image url.'))