# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2019-11-15 14:31
import logging

from django.db import migrations
from django.core.exceptions import ObjectDoesNotExist
from django.forms import model_to_dict

from intranet.femida.src.vacancies.subscriptions.controllers import get_subscription_hash


logger = logging.getLogger(__name__)


def _subscription_to_hash(subscription):
    subscription_hash_fields = (
        'created_by',
        'text',
        'external_url',
        'department',
        'abc_services',
        'professions',
        'pro_level_min',
        'pro_level_max',
        'skills',
        'cities',
        'only_active',
    )
    data = model_to_dict(subscription, subscription_hash_fields)
    return get_subscription_hash(data)


def set_hashes(apps, schema_editor):
    PublicationSubscription = apps.get_model('vacancies', 'PublicationSubscription')
    subscriptions = (
        PublicationSubscription.objects
        .select_related(
            'created_by',
            'department',
        )
        .prefetch_related(
            'abc_services',
            'professions',
            'skills',
            'cities',
        )
        .order_by('-created')  # чтобы из дублей оставить самый свежий
    )

    computed_hashes = set()
    duplicate_subscription_ids = set()
    for subscription in subscriptions:
        sha1 = _subscription_to_hash(subscription)
        if sha1 in computed_hashes:
            duplicate_subscription_ids.add(subscription.id)
            continue
        computed_hashes.add(sha1)

        subscription.sha1 = sha1
        try:
            subscription.save(update_fields=['sha1'])
        except ObjectDoesNotExist:
            logger.info('Skipping as concurrently deleted by user: {}'.format(subscription))
    logger.info('Please, delete all duplicate subscriptions: {}'.format(duplicate_subscription_ids))


class Migration(migrations.Migration):

    dependencies = [
        ('vacancies', '0010_publicationsubscription_hash'),
    ]

    operations = [
        migrations.RunPython(set_hashes, reverse_code=lambda *x, **y: None),
    ]
