from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.db.utils import IntegrityError
from django.utils.module_loading import import_string
from django.utils.translation import gettext_lazy as _


class DirectPayment(models.Model):
    unique_identifier = models.CharField(
        max_length=255, blank=False, null=False, unique=True
    )
    status = models.CharField(
        max_length=255,
        choices=[
            (status, status) for status in settings.OSCAR_ORDER_STATUS_PIPELINE.keys()
        ],
    )
    callback_function = models.CharField(max_length=255, blank=False, null=False)

    def notify_callback(self, amount_paid):
        callback_function = import_string(self.callback_function)
        callback_function(self, self.status, amount_paid)

    @classmethod
    def new(cls, unique_identifier, callback_function, status, amount):
        try:
            instance = cls.objects.create(
                unique_identifier=unique_identifier,
                callback_function=callback_function,
                status=status,
            )
            instance.notify_callback(amount)
            return instance
        except IntegrityError:
            raise ValidationError(_("This payment already exists"))

    @classmethod
    def update_status(cls, unique_identifier, new_status, amount_paid):
        instance = cls.objects.get(unique_identifier=unique_identifier)

        if str(new_status) != str(instance.status):
            instance.status = new_status
            instance.save()

            instance.notify_callback(amount_paid)
