from django.core.management.base import BaseCommand
from django.db import connections
from collections import namedtuple
from establishment.models import Position


def namedtuplefetchall(cursor):
    "Return all rows from a cursor as a namedtuple"
    desc = cursor.description
    nt_result = namedtuple('Result', [col[0] for col in desc])
    return [nt_result(*row) for row in cursor.fetchall()]


class Command(BaseCommand):
    help = 'Add position from old db to new db'

    def position_sql(self):
        with connections['legacy'].cursor() as cursor:
            cursor.execute('''
            select  
                DISTINCT a.`role` as position_name 
            from affiliations as a           
            ''')
            return namedtuplefetchall(cursor)

    def handle(self,  *args, **kwargs):
        objects = []
        for p in self.position_sql():
            count = Position.objects.filter(name={"en-GB": p.position_name}).count()
            if count == 0:
                objects.append(Position(name={"en-GB": p.position_name}))

        p = Position.objects.bulk_create(objects)
        self.stdout.write(self.style.WARNING(f'Created positions objects.'))
