from django.core.management.base import BaseCommand
from django.db import transaction, connection
from django.contrib.auth import get_user_model

from intranet.femida.src.utils.files import iterate_xls
from intranet.femida.src.vacancies.choices import VACANCY_ROLES
from intranet.femida.src.vacancies.models import Vacancy, VacancyMembership


User = get_user_model()


class Command(BaseCommand):

    help = 'Upload main recruiters from sheet (xls/xlsx)'

    def add_arguments(self, parser):
        parser.add_argument('--dry-run', action='store_true')
        parser.add_argument('--input', '-i', action='store', required=True)

    @transaction.atomic
    def handle(self, *args, **options):
        mapping = {}
        rows = iterate_xls(options['input'])
        next(rows)

        for startrek_key, username in rows:
            startrek_key = startrek_key.strip()
            username = username.strip()
            if not startrek_key or not username:
                print('Username: "{}". Ticket: "{}"'.format(username, startrek_key))
                continue
            if startrek_key in mapping:
                print('Duplicating ticket: {}'.format(startrek_key))
            mapping[startrek_key] = username

        vacancies = dict(
            Vacancy.unsafe
            .filter(startrek_key__in=mapping.keys())
            .values_list('startrek_key', 'id')
        )
        users = dict(
            User.objects
            .filter(username__in=mapping.values())
            .values_list('username', 'id')
        )
        # удаление предыдущих Главных рекрутеров для обновляемых вакансий
        if not options['dry_run']:
            memberships_to_delete = VacancyMembership.unsafe.filter(
                role=VACANCY_ROLES.main_recruiter,
                vacancy__in=vacancies.values(),
            )
            memberships_to_delete.delete()

        memberships = []
        for startrek_key, vacancy_id in vacancies.items():
            username = mapping[startrek_key]
            if username not in users:
                print('Not found user {} for vacancy {}'.format(username, vacancy_id))
                continue
            # добавление пользователя на роль Главный рекрутер
            memberships.append(VacancyMembership(
                vacancy_id=vacancy_id,
                role=VACANCY_ROLES.main_recruiter,
                member_id=users[username],
            ))

        if not options['dry_run']:
            VacancyMembership.objects.bulk_create(memberships)
            # Если на одной вакансии один и тот же пользователь в ролях Рекрутер и Главный рекрутер,
            # удаляем у него роль Рекрутер
            sql = """DELETE FROM vacancies_vacancymembership as vm
                WHERE vm.id IN (
                  SELECT vm1.id
                  FROM vacancies_vacancymembership as vm1
                  JOIN vacancies_vacancymembership as vm2
                  ON (
                    vm1.vacancy_id = vm2.vacancy_id
                    AND vm1.role = 'recruiter'
                    AND vm2.role = 'main_recruiter'
                    AND vm1.member_id = vm2.member_id
                  )
                );
            """
            with connection.cursor() as cursor:
                cursor.execute(sql)

        if len(vacancies) < len(mapping):
            missing_tickets = set(mapping.keys()) - set(vacancies.keys())
            print(
                'Not found {} vacancies for tickets: {}'
                .format(len(missing_tickets), ', '.join(missing_tickets))
            )
        print('Successfully updated {} vacancies'.format(len(memberships)))
