import phonenumbers
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _

from ocyan.core.fender import config


def get_from_email(request, form):  # pylint: disable=unused-argument
    return config.get("contact_form", "email_from", settings.DEFAULT_FROM_EMAIL)


def get_to_email(request, form):  # pylint: disable=unused-argument
    to_email = config.get("contact_form", "email_to", settings.DEFAULT_TO_EMAIL)
    return to_email if isinstance(to_email, (list, tuple)) else [to_email]


def validate_phone_number(phone_number):
    """
    Checks phone number with all the country codes and raises error if its invalid
    across all the country codes or supported regions.
    """
    cleaned_number = "".join(c for c in phone_number if c.isdigit() or c == "+")
    if not cleaned_number.startswith("+"):
        all_regions = phonenumbers.SUPPORTED_REGIONS
        for region in all_regions:
            try:
                parsed_number = phonenumbers.parse(cleaned_number, region)
                if phonenumbers.is_valid_number(parsed_number):
                    return
            except phonenumbers.NumberParseException:
                continue
    else:
        try:
            parsed_number = phonenumbers.parse(cleaned_number)
            if phonenumbers.is_valid_number(parsed_number):
                return
        except phonenumbers.NumberParseException:
            pass

    raise ValidationError(_("The phone number entered is not valid."), code="invalid")
