# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models


def forwards_perms(apps, schema_editor):
    """Safely delete content type for old kfet.GlobalPermissions model.

    Any permissions (except defaults) linked to this content type are updated
    to link at its new content type.
    Then, delete the content type. This will delete the three defaults
    permissions which are assumed unused.

    """
    ContentType = apps.get_model("contenttypes", "contenttype")
    try:
        ctype_global = ContentType.objects.get(
            app_label="kfet", model="globalpermissions"
        )
    except ContentType.DoesNotExist:
        # We are not migrating from existing data, nothing to do.
        return

    perms = {
        "account": (
            "is_team",
            "manage_perms",
            "manage_addcosts",
            "edit_balance_account",
            "change_account_password",
            "special_add_account",
        ),
        "accountnegative": ("view_negs",),
        "inventory": ("order_to_inventory",),
        "operation": (
            "perform_deposit",
            "perform_negative_operations",
            "override_frozen_protection",
            "cancel_old_operations",
            "perform_commented_operations",
        ),
    }

    Permission = apps.get_model("auth", "permission")
    global_perms = Permission.objects.filter(content_type=ctype_global)

    for modelname, codenames in perms.items():
        model = apps.get_model("kfet", modelname)
        ctype = ContentType.objects.get_for_model(model)
        (global_perms.filter(codename__in=codenames).update(content_type=ctype))

    ctype_global.delete()


class Migration(migrations.Migration):

    dependencies = [
        ("kfet", "0054_delete_settings"),
        ("contenttypes", "0001_initial"),
        ("auth", "0001_initial"),
    ]

    operations = [
        migrations.AlterModelOptions(
            name="account",
            options={
                "permissions": (
                    ("is_team", "Is part of the team"),
                    ("manage_perms", "Gérer les permissions K-Fêt"),
                    ("manage_addcosts", "Gérer les majorations"),
                    ("edit_balance_account", "Modifier la balance d'un compte"),
                    (
                        "change_account_password",
                        "Modifier le mot de passe d'une personne de l'équipe",
                    ),
                    (
                        "special_add_account",
                        "Créer un compte avec une balance initiale",
                    ),
                )
            },
        ),
        migrations.AlterModelOptions(
            name="accountnegative",
            options={"permissions": (("view_negs", "Voir la liste des négatifs"),)},
        ),
        migrations.AlterModelOptions(
            name="inventory",
            options={
                "ordering": ["-at"],
                "permissions": (
                    (
                        "order_to_inventory",
                        "Générer un inventaire à partir d'une commande",
                    ),
                ),
            },
        ),
        migrations.AlterModelOptions(
            name="operation",
            options={
                "permissions": (
                    ("perform_deposit", "Effectuer une charge"),
                    (
                        "perform_negative_operations",
                        "Enregistrer des commandes en négatif",
                    ),
                    ("override_frozen_protection", "Forcer le gel d'un compte"),
                    ("cancel_old_operations", "Annuler des commandes non récentes"),
                    (
                        "perform_commented_operations",
                        "Enregistrer des commandes avec commentaires",
                    ),
                )
            },
        ),
        migrations.RunPython(forwards_perms),
    ]
