import logging

from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver

from oscar.core.loading import get_model

from ocyan.plugin.oscar_checkout.plugins import get_payment_method_choices

logger = logging.getLogger(__name__)

PaymentMethod = get_model("checkout", "PaymentMethod")
Country = get_model("address", "Country")


def setup_payment_methods(sender, app_config, **kwargs):
    try:
        methods = get_payment_method_choices()

        for key, label in methods:
            try:
                payment_method, created = PaymentMethod.objects.get_or_create(
                    key=key, defaults={"label": label}
                )
                if created:
                    logger.info("Created payment_method key=%s label=%s.", key, label)
                    payment_method.country.set(Country.objects.all())
            except PaymentMethod.MultipleObjectsReturned:
                pass  # multiple is at least one so nomatter.
    except Exception as e:  # pylint: disable=W0703
        logger.exception(e)


@receiver(post_save, sender=PaymentMethod)
def handle_payment_method_change(sender, instance, raw, **kwargs):
    if not raw:  # don't run this hook when loading a fixture
        if instance.requires_permission:
            ctype = ContentType.objects.get_for_model(sender)
            Permission.objects.get_or_create(
                codename=instance.key,
                content_type=ctype,
                defaults={"name": "Allow %s" % instance.label},
            )
