from django.core.management.base import BaseCommand
from django.db import connections
from establishment.management.commands.add_position import namedtuplefetchall
from establishment.models import Establishment, Position, Employee, EstablishmentEmployee


class Command(BaseCommand):
    help = '''Add employee position from old db to new db.
    Run after add_position and add_employee!'''

    def empl_position_sql(self):
        with connections['legacy'].cursor() as cursor:
            cursor.execute('''
                                select t.id,
                                       t.profile_id,
                                       t.establishment_id, 
                                       t.role, 
                                       t.start_date, 
                                       t.end_date
                                from 
                                    (
                                        select  
                                            DISTINCT
                                            a.id, 
                                            a.profile_id,
                                            a.establishment_id, 
                                            a.role, 
                                            a.start_date, 
                                            a.end_date,
                                            trim(CONCAT(p.firstname,  ' ', p.lastname)
                                                ) as name
                                        from affiliations as a
                                        join profiles p on p.id = a.profile_id
                                    ) t 
                                where t.name is not null               
            ''')
            return namedtuplefetchall(cursor)

    def handle(self, *args, **options):
        objects = []
        for e in self.empl_position_sql():
            pos = Position.objects.filter(name={"en-GB": e.role}).first()
            empl = Employee.objects.filter(old_id=e.profile_id).first()
            est = Establishment.objects.filter(old_id=e.establishment_id).first()
            if pos and empl and est:
                est_empl = EstablishmentEmployee(
                    from_date=e.start_date, to_date=e.end_date,
                    old_id=e.id
                )
                est_empl.establishment = est
                est_empl.employee = empl
                est_empl.position = pos
                objects.append(est_empl)

        ee = EstablishmentEmployee.objects.bulk_create(objects)
        self.stdout.write(self.style.WARNING(f'Created employee position objects.'))
