from django.core.exceptions import ValidationError
from django.test import TestCase
from django.test.client import RequestFactory

from ocyan.main.loading import get_ocyan_class

from .utils import validate_phone_number

ContactForm = get_ocyan_class("contact_form.forms", "ContactForm")


class ContactFormSmokeTestCase(TestCase):
    def test_backwards_compatibility(self):
        """
        We added the request as form argument, but if projects have the form overidden without extending
        the form class from this plugin, it will break. This test makes sure that projects that have this
        break in Jenkins and that we don't figure this out once released.
        """
        request = RequestFactory().get("/")
        try:
            ContactForm(request=request)
        except TypeError as e:
            if "unexpected keyword argument 'request'" in str(e):
                self.fail(
                    "ContactForm now receives a request object as argument, adjust the form by adding self.request = kwargs.pop('request'', None) to the init method (before calling super)"
                )


class PhoneNumberValidationTestCase(TestCase):
    def test_phone_number_validation(self):
        validate_phone_number("123-456-7890")
        validate_phone_number("(555) 123-4567")
        validate_phone_number("9876543210")
        validate_phone_number("12345")
        validate_phone_number("+442071234567")
        validate_phone_number("01234567890")

        with self.assertRaises(ValidationError):
            validate_phone_number("123")

        with self.assertRaises(ValidationError):
            validate_phone_number("SDFFdd")

        with self.assertRaises(ValidationError):
            validate_phone_number("SDFF++dd")

        with self.assertRaises(ValidationError):
            validate_phone_number("+0")
