# -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2019-04-01 10:53
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations

from weblate.accounts.data import create_default_notifications
from weblate.accounts.notifications import FREQ_INSTANT, SCOPE_DEFAULT

MAPPING = [
    ("subscribe_any_translation", ("ChangedStringNotificaton",)),
    ("subscribe_new_string", ("NewStringNotificaton",)),
    ("subscribe_new_suggestion", ("NewSuggestionNotificaton",)),
    ("subscribe_new_contributor", ("NewContributorNotificaton",)),
    ("subscribe_new_comment", ("NewCommentNotificaton",)),
    ("subscribe_merge_failure", ("MergeFailureNotification", "ParseErrorNotification")),
    ("subscribe_new_language", ("NewTranslationNotificaton",)),
]


def migrate_subscriptions(apps, schema_editor):
    Profile = apps.get_model("accounts", "Profile")
    db_alias = schema_editor.connection.alias
    profiles = Profile.objects.using(db_alias).all().select_related("user")
    profiles = profiles.exclude(user__username=settings.ANONYMOUS_USER_NAME)
    for profile in profiles:
        user = profile.user
        create_default_notifications(user)
        for flag, notifications in MAPPING:
            if getattr(profile, flag):
                for notification in notifications:
                    user.subscription_set.get_or_create(
                        scope=SCOPE_DEFAULT,
                        notification=notification,
                        defaults={"frequency": FREQ_INSTANT},
                    )


class Migration(migrations.Migration):

    dependencies = [("accounts", "0005_auto_20190331_2126")]

    operations = [
        migrations.RunPython(
            migrate_subscriptions, migrations.RunPython.noop, elidable=True
        )
    ]
